Laravel 8.x Eloquent Model Query Scope Example

Local and global scopes in Eloquent allow you to define prebuilt “scopes” (filters) that you can use either every time a model is queried (“global”) or every time you query it with a particular method chain (“local”).

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 8 and how it will easy for you. i will guide you to create custom query function in model eloquent using scope in laravel 6. You can easily use dynamic query scope in laravel 8 application.

In this tutorial i will show you from scratch how to use eloquent scope in laravel 8 application. If you don't know how to use laravel eloquent model scope, then i will help you to learn clearly from this laravel model query scope example.

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

namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    public $table = "posts";
      
    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];
  
    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();

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

namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    public $table = "posts";
      
    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];

    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.

 

Read also : Learn How to Use Scopes in Laravel

 

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

 

Hope this tutorial will help you. 

 

#laravel #scope #laravel-6 #laravel-eloquent