The introduction

In principle, code is written once and references are everywhere. There is no need for a lot of redundant code. This is a trend and also the direction of efforts to improve the robustness of code. The Laravel model provides us with a layer of database manipulation that separates data interactions.

But over time, as the requirements of the project continue to expand, the most common query operations, there will also be a lot of redundant code.

This article will talk about, even the model of self-slimming, reduce the model code.

Global scope

Assuming that some database query operations, whether in a controller, a template file, or a command line method, have repeated usage requirements, these filters can be added by default if there is a common method in the model, which can significantly reduce the amount of code.

For example, there is a query condition:

$publishedEvents = Event::where('published'.'='.1)->get();
Copy the code

The resulting SQL statement from the above code is as follows:

SELECT * FROM events WHERE `published` = 1;
Copy the code

If the condition published = 1 needs to be turned on by default, we can append this condition to all queries using the laravel model’s global scoping approach.

Introduce the following classes in the model file Event header:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
Copy the code

Inside the model class, implement the boot method manually:

protected static function boot()
{
    parent::boot();
    static::addGlobalScope('published'.function (Builder $builder) {
    	$builder->where('published'.'='.1);
    });
}
Copy the code

The SQL statement WHERE published = 1 is appended to all model query methods, and the constraint statement is appended to all queries that create QueryBuilder objects.

Some readers may be asking, “If I don’t want this constraint, won’t the model ever work?”

How can I! It’s just an element in an array of QueryBuilder properties that can be removed manually to solve the special case.

$events = Event::withoutGlobalScopes()->get();
Copy the code

You see, append is easy, remove is even easier.

Local scope

The withoutGlobalScope that follows the next section is masked manually in a different way each time, and sometimes using a limited scope is a better solution. As a result, local scopes are created, and methods that are specific to a model file are invoked manually and not actively appended.

To declare a local scope, just follow Laravel’s syntax, as shown in the following example:

public function scopePublished($query)
{
	return $query->where('published'.1);
}
Copy the code

You simply declare a function method with a small camel name starting with Scope and return an instance of a QueryBuilder object. Call to manually append:

$events = Event::published()->get();
Copy the code

The **published()** method is mapped to the scopePublished method.

The demo code above does not accept user input, so here is how to pass parameters. For example, there is a query requirement like this:

$events = Event::where('zip'.$zipCode)->get();
Copy the code

Use local scope to implement:

public function scopeZip($query.$zip)
{
	return $query->where('zip'.$zip);
}
Copy the code

Pass in by position. The use of, passed in directly:

$zip = '43016';
$events = Event::zip($zip)->get();
Copy the code

This completes the use of the local scope, isn’t it intuitive?

Since the local scope returns an instance of QueryBuilder, it is natural to chain-call the local scoped method and the QueryBuilder method. Let’s declare another local scoped method:

public function scopeAttendees($query.$maximum)
{
	return $query->where('max_attendees'.$maximum);
}
Copy the code

Now use the two methods in tandem:

$events = Event::zip(43016)->attendees(2)->get();
Copy the code

The generated SQL statement is as expected:

SELECT * FROM events WHERE zip = '43016' and max_attendees = '2';
Copy the code

Write in the last

In this issue, we went over the laravel model’s scope design method. Two methods are described:

  • Global scope: it is global and needs to be removed manually.

  • Local scope: only manual calls work and can be chained;

Such a design pattern can greatly save query code, but for maintenance, equally familiar developers need to follow each other’s development specifications and write maintainable code.

Happy coding 🙂

I am a @programmer assistant, an original author in the IT field who focuses on programming knowledge and circle dynamics

🏆 nuggets technical essay | double festival special articles