How to Create and Use Query Scope in Laravel Eloquent

By Hardik Savani April 16, 2024 Category : Laravel

Today, i would like to share example of how to use laravel eloquent model scope. i will show you how to create model eloquent query scope in laravel 6 and how it will easy for you. i will guide you to create custom query function in model eloquent using scope in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 app.

You can easily use dynamic query scope in laravel 6 application.

Sometime, we are working model query like get todays records, get active records, get banned users etc. At this time we always use where condition everywhere on controller file. i think where condition is right it is not wrong, but you have to write if again and again with some login like current date and etc. If you create laravel model eloquent scope then you don't have to write same logic with where condition again and again. You can just use function like "latest()". You can easily re-use that scope on your model query.

Here i will give you simple with today() scope and it will get only today records. So let's see this example here:

Create Scope in Model

Here, we will add today scope in our post model. So when we query in controller then we will use that scope in laravel model.

app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

public $table = "posts";

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'id', 'title', 'body', 'status'

];

/**

* Scope a query to only include popular users.

*

* @param \Illuminate\Database\Eloquent\Builder $query

* @return \Illuminate\Database\Eloquent\Builder

*/

public function scopeToday($query)

{

return $query->whereDate('created_at', \Carbon\Carbon::today());

}

}

Use Scope Query

Now you can see how you can use that with your controller file.

Post::select("*")->today()->get();

Dynamic Scope in Model

Here, we will add today scope in our post model. So when we query in controller then we will use that scope in laravel model.

app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

public $table = "posts";

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'id', 'title', 'body', 'status'

];

/**

* Scope a query to only include popular users.

*

* @param \Illuminate\Database\Eloquent\Builder $query

* @return \Illuminate\Database\Eloquent\Builder

*/

public function scopeStatus($query, $type)

{

return $query->where('status', $type);

}

}

Use Scope Query

Now you can see how you can use that with your controller file.

Post::select("*")->status(1)->get();

I hope it can help you...

Shares