Laravel 10 Use Scopes in Laravel

Hello Artisan, today I'll show you how to How to Using Scopes in Laravel. Laravel offers a variety of useful tools that you can use on your Eloquent queries to narrow down the results. Encountering scenarios where you need to reuse certain conditions is common. To simplify this process in Laravel models, you can make use of "Scopes," which enable you to encapsulate conditions for readability and reusability. In this article, I'll demonstrate how to seamlessly integrate scopes into your Laravel models.

Table of Contents

  1. Creating Scopes in Laravel
  2. Creating Dynamic Scopes in Laravel
  3. Using Scopes with Relations

Creating Scopes in Laravel

Here's a simplified version of that condition to retrieve completed projects: "Get all projects that are marked as completed."

$completedProjects = Project::where('completed', 1)->get();

You might need to use the condition mentioned above in different parts of your application. To avoid repetition, you can use Laravel scopes. A scope is like a method in your model that wraps the query syntax used in the example you provided. Scopes are created by adding the word "scope" as a prefix to a method name, like this.

class Project extends Model
    public function scopeCompleted($query)
        return $query->where('completed', 1);


With the scope defined above, you can execute it like so:

$completedProjects = Project::completed()->get();

Creating Dynamic Scopes in Laravel

If you'd like to make the scope adjustable and include projects that haven't been finished, you can provide an argument. Just create an input parameter, similar to how you would for any other method in a model.

class Project extends Model {

    public function scopeCompleted($query, $arg)
        return $query->where('completed', $arg);

With the input parameter defined, you can use the scope like this:

// Get completed projects
$completedProjects = Project::completed(1)->get();

// Get incomplete projects
$nonCompletedProjects = Project::completed(0)->get();

Using Scopes with Relations

You might often need to use scopes along with relations. For example, you can get a list of projects that are connected to a user:

$user = User::findOrFail(1); // 1 is user id
$completedProjects = $user->projects()->completed(1)->get();

Laravel scopes are super handy when you've got certain queries you keep using over and over. They let you write the code once and then use it again whenever you need without any fuss.

That's it for today. I hope it'll be helpful in the upcoming project.