Skip to content
Advertisement

How to make my post featured in Laravel 9

I have made a create post function and I would like to make a certain section only have a featured post. I’m new to laravel and php so was not to sure how to do it. I created a featured column in my db and passed a foreach($posts as $featured) into the section I wanted featured. From my research, the idea I saw was to toggle between a default value of “0” and a featured value of “1”. Not sure where to go from there

EDIT: using the ->default(0) and re-running the migration did the trick. Now the question is how I can toggle between 0 and 1

Route:

// Store Listing Data
Route::post('/posts', [PostsController::class, 'store']);

Posts Controller (Create function):

public function store(Request $request) {
    $formFields = $request->validate([
        'title' => 'required',
        'sub_title' => 'nullable',
        'tags' => 'required',
        'content' => 'required',
        'featured' => 'nullable',
    ]);

    Posts::create($formFields);

    return redirect('/'); 
}

Posts Model

protected $fillable = ['title', 'sub_title', 'tags', 'content','featured'];

Advertisement

Answer

You are on a right way! Your column must be tinyint and it will accept values of 1 and 0. 1 means the post is featured and 0 means its a normal post. Your migration must look like this

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    // ...
    $table->tinyInteger('featured')->default(0);
    // ...
    $table->timestamps();
});

Now when you insert a post it will be automatically inserted as a normal post. If you want the post to be inserted as featured you must declare it while inserting the post like this:

Post::create([
   'title' => 'My first post',
   'sub_title' => 'I am so glad I published this post',
   'tags' => 'first_post , so_glad',
   'content' => 'My first post contents',
   'featured' => 1 // THIS MEANS THE POST WILL BE FEATURED
]);

And then whenever you want to retrieve all featured posts you can do

Post::where('featured', 1)->get();

That’s it! Now you listed all the featured posts!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement