Laravel – Scopes (3 Easy Steps)

Laravel

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!

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

whereDate('created_at', \Carbon\Carbon::today()); } }

Step 2: Use the scope in your controller

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

Post::today()->get();

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); }

Use Both in your controller!

Post::status(1)->today()->get();

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!

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.

0 Comments

You may find interest following article

Complete Guide: Create Laravel Project in Docker Without Local Dependencies

Create Laravel Project Through Docker — No Need to Install PHP, MySQL, or Apache on Your Local Machine In this tutorial, I’ll show you how to create and run a full Laravel project using Docker containers. That means you won’t have to install PHP, MySQL, or Apache locally on your computer. By the end of this guide, you’ll have a fully functional Laravel development...