Laravel news feed
A Laravel news feed! Here's a basic example of how you can create a news feed in Laravel:
Step 1: Create a News Model and Migration
Create a new model and migration for your news articles:
php artisan make:model News -m
In the News
model, add the following code:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = [
'title',
'description',
'published_at',
];
}
In the news
migration file, add the following code:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateNewsTable extends Migration
{
public function up()
{
Schema::create('news', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamp('published_at');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('news');
}
}
Step 2: Create a News Feed Controller
Create a new controller for your news feed:
php artisan make:controller NewsFeedController
In the NewsFeedController
, add the following code:
namespace App\Http\Controllers;
use App\Models\News;
use Illuminate\Http\Request;
class NewsFeedController extends Controller
{
public function index()
{
$news = News::latest()->paginate(10);
return view('news.feed', compact('news'));
}
}
Step 3: Create a News Feed View
Create a new view for your news feed:
// resources/views/news/feed.blade.php
<h1>News Feed</h1>
<ul>
@foreach($news as $article)
<li>
<h2>{{ $article->title }}</h2>
<p>{{ $article->description }}</p>
<p>Published at: {{ $article->published_at }}</p>
</li>
@endforeach
</ul>
{!! $news->links()!!}
Step 4: Define Routes
In your routes/web.php
file, add the following code:
Route::get('/news', 'NewsFeedController@index');
Step 5: Run Migrations and Seed Data
Run the following commands to create the database tables and seed some sample data:
php artisan migrate
php artisan db:seed --class=NewsSeeder
Step 6: Test Your News Feed
Open your browser and navigate to http://localhost/news
to see your news feed in action!
This is a basic example of how you can create a news feed in Laravel. You can customize and extend this example to fit your specific needs.
Some additional features you might want to consider adding to your news feed include:
- User authentication and authorization to allow users to create and manage their own news articles
- Commenting and liking system to allow users to interact with each other's news articles
- Filtering and sorting options to allow users to customize their news feed experience
- Integration with social media platforms to allow users to share their news articles on other platforms
- And more!