Once you start diving into the Laravel documentation you’ll find a lot of features that aren’t much talked about in the docs. Other features are used less frequently and chances are that you’re unaware of these features.

Models aren’t any different. If you look at the Laravel API documentation you’ll be surprised and probably overwhelmed by all the properties and methods that are available for models.

There are a lot of powerful and easy to use features available, that not everybody is aware of. That’s exactly why we’ll go over these 7 tips that every developer that’s using Laravel should know to get the most of their models.

1. Custom Cast Types

Custom cast types were introduced in Laravel 7. In earlier versions of Laravel, you’re pretty limited when it comes to the casting of attributes. You could only cast to a default set which was provided by Laravel.

Although there were some packages available that implemented custom casting, they had one major drawback. These packages override the getAttribute and setAttribute method which means they can’t be combined with other packages that also override these methods.

This is how you used the casts property before Laravel 7:

protected $casts = [
    'is_admin' => 'boolean',
    'date_of_birth' => 'date'
];

From Laravel 7 you have the option to add a custom cast type. You can do this by creating a custom cast class that implements the CastsAttributes interface. This interface forces you to implement a get and a set method.

The get method is responsible for transforming a raw value from the database into a cast value. The set method handles the transformation of a cast value into a raw value that can be stored in the database.

This is what a custom cast type that handles JSON could look like:

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

You can attach the custom cast type to a model attribute by using the class name of the custom cast type.

use App\Casts\Json;

// More code
protected $casts = [
    'is_admin' => 'boolean',
    'date_of_birth' => 'date',
    'settings' => Json::class,
];

#laravel #web-development #php

Get The Most Out of Your Laravel Models with 7 Tips
4.10 GEEK