Laravel 7/6 Eloquent Local Scope Tutorial Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

557

27-12-2019


Hi Guys,

In this Example,how to use the local scope in laravel 7/6. I will show you how to create model eloquent query scope in laravel 7/6. you will simply use to local scope in laravel 7/6.

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

we are working model query like get todays records, get active records, get banned users etc. If you create laravel model eloquent scope then you don't have to write same logic with where condition again and again.

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

Create Local Scope in Model

you will add today scope in our post model. So when you query in controller then you 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 Local Scope Query

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

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

Dynamic Local 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 Local Scope Query

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

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

It will help you....


Recommended Posts