6 useful tips to boost your Laravel code
Tags: webdev, laravel, php
Published: 2021-03-01 08:07:52

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 <a href="https://laravelbit.com">laravelbit</a>. 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:

```php
$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:

```php
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:

```php
$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:

```php
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:

```php
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:

```php
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.

```php
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:

```php
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:

```php
$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:

```php
$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:

```php
$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:

```php
$activeInvoices = $invoices->reject(function ($invoice) {
    return $invoice->paid;
});
```

We can also use the filter method for the same task:

```php
$activeInvoices = $invoices->filter(function ($invoice) {
    return $invoice->paid;
});
```

For another example, let's get the first item from the Collection that matches a condition:

```php
$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 <a href="https://laravelbit.com">laravelbit</a>.