1. Create Scopes in the model
<?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());
}
}
2. Using Scopes in Controllers
Post::today()->get();
3. Make Scopes dynamic by adding parameters
/**
* Scope created awhile ago
*/
public function scopeToday($query)
{
return $query->whereDate('created_at', \Carbon\Carbon::today());
}
/**
* New Dynamic Scope
*/
public function scopeStatus($query, $type)
{
return $query->where('status', $type);
}
4. Use both in the controller
Post::status(1)->today()->get();
Post comment 取消回复