How to Create and Use Query Scope in Laravel Eloquent
Today, i would like to share example of how to use laravel query scope in laravel. i will guide you to create custom query function in model using scope in laravel app.
You can easily use dynamic query scope in laravel application.
Buy traffic for your websiteSometime, 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. 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.Buy traffic for your website
- Create Scope in Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $table = "users";
protected $fillable = [
'id', 'name', 'email', 'status'
];
public function scopeToday($query)
{
return $query->whereDate('created_at', \Carbon\Carbon::today());
}
}
- Use Scope Query
User::select("*")->today()->get();
- Dynamic Scope in Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $table = "users";
protected $fillable = [
'id', 'name', 'email', 'status'
];
public function scopeStatus($query, $type)
{
return $query->where('status', $type);
}
}
- Use Scope Query
User::select("*")->status(1)->get();
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $table = "users";
protected $fillable = [
'id', 'name', 'email', 'status'
];
public function scopeToday($query)
{
return $query->whereDate('created_at', \Carbon\Carbon::today());
}
}
User::select("*")->today()->get();
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $table = "users";
protected $fillable = [
'id', 'name', 'email', 'status'
];
public function scopeStatus($query, $type)
{
return $query->where('status', $type);
}
}
User::select("*")->status(1)->get();
👌👌
ReplyDelete