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:

JavaScript

Posts Controller (Create function):

JavaScript

Posts Model

JavaScript

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

JavaScript

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:

JavaScript

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

JavaScript

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

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