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();
点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部