When working with any programming language or framework, you can utilize certain tips & tricks to enhance your coding level and make your application more performant and your code more elegant. The more you use certain design principles and best practices, the more you will grow as a developer. As I am a professional Laravel/Vue developer, I have created a free resource where I publish weekly Laravel tips called laravelbit. In this article, I will show you some of them and, hopefully, you can use them to supercharge your Laravel applications. Here we go!
1. Make your code more elegant using Eloquent query scopes
Often, when using Eloquent ORM in our Laravel applications, we need to match certain conditions when working with data. For example, consider this query:
$active_administrators = User::where('active', '=', 1)->where('is_admin', '=', 1)->get();
One might easily use these conditions in many locations throughout our application. In order to make our code more readable and not be repetitive, we can use query scopes. For our example, we would create the following functions in our User model:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeAdmin($query)
{
return $query->where('is_admin', '=', 1);
}
Now, our original query would look like this:
$active_administrators = User::active()->admin()->get();
2. Set column value automatically on model create
There are some situations in which you want to set a certain column automatically when creating a new record. In order to achieve this, you can use the model's creating event inside the boot method of the model. In this example, we set the value of column paid to 0 (false) on the Invoice model for each record we create:
class Invoice extends Model {
protected static function boot()
{
parent::boot();
Invoice::creating(function($model) {
$model->paid = 0;
});
}
}
3. Avoid errors by using the optional helper
When accessing object values, if that object is null, your code will raise an error. For example:
return $invoice->total;
Would raise an error if the invoice object was empty. A simple way of avoiding errors is to use the optional Laravel helper:
return optional($invoice)->total;
Now, if the $invoice object is null, your code will return null instead of raising an error. You may also use a closure with the optional helper. It receives the closure as it's second argument and it will be called if the first argument is not null.
return optional(Invoice::find($id), function ($invoice) {
return $invoice->total;
});
4. Deleting related records automatically
During the design of application databases, it's typical to create related tables. When deleting parent records, it is also standard practice and a good database design principle to delete child related records as well. To achieve this in Laravel, we can use the model's deleting event inside the boot method of the model. For example, to delete all items of an invoice:
class Invoice extends Model
{
public function items()
{
return $this->hasMany('\App\Models\Item');
}
public static function boot() {
parent::boot();
static::deleting(function($invoice) {
foreach ($invoice->items as $item) {
$item->delete();
}
});
}
}
5. Update or create
While working with databases, it is common to check if a certain record exists and update it accordingly, or create a new record otherwise. Something like this:
$invoice = Invoice::where('active', 1)
->where('client', 'My client')
->where('price', 49)
->first();
if ($invoice) {
$invoice->update(['price' => 29]);
}
You can use Eloquent's updateOrCreate method instead:
$invoice = Invoice::updateOrCreate(
['active' => '1', 'client' => 'My client'],
['price' => 29]
);
6. Use Laravel Collection methods
Collections is a huge feature offered by Laravel out of the box which allows us to easily manipulate array data types. It can be a big time saver and utilizes a simple and intuitive syntax. It is particularly useful when combining it with Eloquent. For example, if you have an Eloquent query like this:
$invoices = Invoice::where('active', 1)
->orderBy('total')
->take(10)
->get()
Maybe we want to remove all invoices which were paid from our database selection; essentially filtering them to include only unpaid invoices. We could use Collection's reject method:
$activeInvoices = $invoices->reject(function ($invoice) {
return $invoice->paid;
});
We can also use the filter method for the same task:
$activeInvoices = $invoices->filter(function ($invoice) {
return $invoice->paid;
});
For another example, let's get the first item from the Collection that matches a condition:
$activeInvoices = $invoices->first(function ($invoice) {
return $invoice->paid;
});
Using tips like this while developing your application is important as it improves your code efficiency and readability. If you would like to regularly get new Laravel tips, go to laravelbit.
Top comments (7)
As of PHP 8 you can use the null-safe operator.
Thank you for the article, I really like the tips mentioned, especially the query scopes, which are a nice way to reduce repetition in Repositories for your app.
My eye just caught something while reading the article, shouldn't the filter method be used as (for filtering unpaid invoices in your example):
$activeInvoices = $invoices->filter(function ($invoice) {
return !$invoice->paid;
});
With the
!
It seems weird that the condition in the closure for the
reject
and thefilter
function are the same.I really like the format of your new site. I just have 2 suggestions though. Tags and a RSS feed would make it really awesome.
Good job
I plan on implementing both soon! Thanks!
I have visited your website laravelbit.com. And it is absolutely amazing. Keep it up bro!
Thanks!
Good tips, thanks, but sadly your website is inaccessible :(