Friday, February 28, 2020

Using Eloquent Query Scopes with Laravel

Using Eloquent Query Scopes with Laravel


Today I want to give an example of how the scope of the eloquent Laravel model can be used. I'll show you how to create an eloquent model query area in Laravel 6 and how it will be easy for you. I will guide you to create a custom query function in the eloquent model using the 6 range in Laravel.

You can easily use the dynamic query range in the Laravel 6 application.

At some point we will be working on model requests such as retrieving records today, retrieving active records, retrieving prohibited users, etc. At this point, we use whatever condition anywhere in the controller file. I think if the state is correct it is not bad, but you should always write with a login like the current date etc. and again you can use functions like "latest ()". You can easily reuse this area in your model query.

Here I give you a simple range with today () and you only get records today. Let's look at this example here:

Generate Scope in Model


Here we will expand the scope of our publication model today. So if we check the controller, we will use this area in the 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 Scope Query


Now you can see how to use that with your driver file.

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


Dynamic Scope in Model


Here we will expand the scope of our publication model today. So if we check the controller, we will use this area in the 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 Scope Query


Now you can see how to use that with your driver file.

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


I hope this could help you ...

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.