DEV Community

Cover image for Laravel 8 - Scopes (3 Easy Steps)
DaleLanto
DaleLanto

Posted on

Laravel 8 - Scopes (3 Easy Steps)

Scoping is one of the superpowers that eloquent grants to developers when querying a model. Scopes allow developers to add constraints to queries for a given model.

In simple terms laravel scope is just a query, a query to make the code shorter and faster. We can create custom query with relation or anything with scopes.

In any admin project we need to get data using status base, just like active, pending, draft something else. Instead of writing the same query everytime just use scopes and you're done!

Image description

Let's Start Creating our Scope!

Let's create a simple with today() scope and it will get only today records.

Step 1: Create Scope in Model

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";

    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];

    public function scopeToday($query)
    {
        return $query->whereDate('created_at', \Carbon\Carbon::today());
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Use the scope in your controller

Go to you controller and use the scope by pasting this:

Post::today()->get();
Enter fullscreen mode Exit fullscreen mode

We can also include parameters to make the scope more dynamic!

Step 3: Make the Scope Dynamic by Adding Parameters

Lets go back to the model and add parameters to the scope

app/Post.php

/**
     * 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);
    }
Enter fullscreen mode Exit fullscreen mode

Use Both in your controller!

Post::status(1)->today()->get();
Enter fullscreen mode Exit fullscreen mode

Hurray! We have succesfully created our scopes (local scopes) and used it, now use it to your projects and make your code more readable and stable!

Image description

I don't recommend the usage of Global Scopes because it can mess up the readability of queries when you are working with a team, specially if there are new members of the team.

But if you want to use it click here

Instead just use Local Scopes which we discussed here and you are good to go!

Image description

Discussion (0)