LARAVEL

Simplified Eloquent Global Scopes in Laravel 5.2


This is a series of posts that showcase new features and aha moments in Laravel 5.2

1. Implicit Route Model Binding

2. Simplified Eloquent Global Scopes

3. Append Scheduled Tasks Output

4. Form Array Validation

5. Middleware Groups

6. Auth Scaffolding

7.  Api Rate Limiting

8. More helper functions

The use of Eloquent Global scopes has been greatly simplified in Laravel 5.2

Several Laravel Developers love to use the simple scopes to avoid duplicating queries everywhere in the code base.

Let’s take a simple look at Local Scopes

Let’s assume we have a Task Model.

Task.php

So in my controllers, I can do:

Task::finish()->get() , this will actually return all the finished tasks.

That’s a quick refresher on Local Scopes.

Now, Let’s take a close look at Global Scopes.

In Laravel 5.2, It’s simple to create Global Scopes. There are two ways of going about it:

1. Create a separate class.

2. Use a closure inside the Model to define the Global Scope.

Method 1

Create Folder called Scopes in the app directory. Let’s create a FinishScope file in it like so:

FinishScope.php

Let me explain.

1. We defined a class that implements the Illuminate\Database\EloquentScope interface. This interface requires one to implement the apply method.

The apply method is where the query happens.

Now, we can apply this Global Scope to any given model by overriding its boot method and use the addGlobalScope method.

Let’s try it on the Task Model.

Task Model

Now that we have added the scope to the Task Model, running Task::all() will return all finished tasks because it will run this query:

Method 2

Task Model

This is called an anonymous Global Scope. 

If you don’t want to involve the Global Scope in a query, you can just call the withoutGlobalScope method like so:

Task::withoutGlobalScope('finish')->get()

Conclusion

It’s that simple to use Global Scopes in Laravel 5.2

Please let me know if you have any questions or observations in the comments section below:

 

 

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.