The Cult of the Child

Today felt like a jeans day, with the comfy stretchy bit of my hand-me-down maternity pair pulled over my ballooning belly, worn with flip flops, naturally. We have left the September mini heat-wave…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How to create and use the model scope in Laravel Eloquent?

Today I would like to share an example of How to create and use the model scope in laravel Eloquent. I will guide you to create a custom query function in model eloquent using the scope in laravel 6, laravel 7, and laravel 8 app.

Sometimes we are working on a laravel eloquent query like getting today’s records, get all active or Inactive records or some conditional statement(Where) that can be used many times. so in this situation, we have to write where condition again and again. so to get rid of this issue laravel has an awesome feature called laravel eloquent model scope. so you can write a function that starts with “scopeFunctionName” and you can reuse it everywhere in the controller with that model.

Okay, so now let understand this concept with an example. Here I will give a very basic example to fetch all posts that have been posted today.

Here, we will add today scope in app/Models/Post.php. So when we query in the controller then we will use that scope in the laravel model.

Here I have defined a method scopeStaus and I have passed parameter $status.

That’s it, I hope it will help you.

Add a comment

Related posts:

Delete Invalid Phone Numbers From Your Database Using An aPI

Do you want to delete invalid phone numbers from your database? If the answer is yes, you should use an API! You may not know; but almost five percent of the numbers that are registered each year are…

Recruiters and LinkedIn

Looking at and actively applying for the job is a different challenge. And, while we all do this, it is said that you should “Network, connect and ask for help” as much as you can. Being among the…

Follow the Leader

I was fishing the mouth of Willow Creek using a florescent Daredevil and had a sliver on nearly every cast. Other anglers were not so fortunate. I held the hot rod and had the only Daredevils. I…