Elegant accessors and modifiers in Laravel

WBOY
Release: 2023-08-29 22:54:01
Original
1104 people have browsed it

Elegant accessors and modifiers in Laravel

In this article, we will introduce the modifiers and accessors of the Eloquent ORM in the Laravel web framework. After the introduction, we will understand these concepts through some examples.

In Laravel, modifiers and accessors allow you to change data before saving it to or getting data from the database. Specifically, mutators allow you to change data before saving it to the database. Accessors, on the other hand, allow you to change data after getting it from the database.

In fact, the Laravel model is the central place where you can create modifier and accessor methods. Of course, it's nice to have all your modifications in one place instead of scattered in different places.

Create accessors and modifiers in the model class

Now that you are now familiar with the basic concepts of modifiers and accessors, we will move on to develop a practical example to demonstrate it.

I assume you understand Eloquent models in Laravel, we will use the Post model as a starting point for the example. If you haven't created the Post model yet, let's use the artisan command to create it.

php artisan make:model Post --migration
Copy after login

This should create a model file in app/Post.php as shown below.

<?php
 
namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    //
}
Copy after login

Let’s replace the contents of this file with the following.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Post extends Model
{
    /**
     * Interact with the user's name attribute.
     *
     * @param  string  $value
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ucfirst($value),
            set: fn ($value) => strtolower($value),
        );
    }
}
Copy after login

Since we used the --migration option, it should also create associated database migrations. Just in case you don't know, you can run the following command so that it actually creates the table in the database.

php artisan migrate
Copy after login

In order to run the examples in this article, you need to create the name column in the post table. In any case, we will not go into the details of the migration as that is beyond the scope of this article.

Mutator method

First, let’s take a look at the mutator method.

protected function name(): Attribute
{
    return Attribute::make(
        #get: fn ($value) => ucfirst($value),
        set: fn ($value) => strtolower($value),
    );
}
Copy after login

As we discussed before, modifiers are used to change data before saving it to the database. As you can see, the syntax of a mutator method is {attribute-name}. Of course, you need to replace {attribute-name} with the actual attribute name in camel case. It is important to note that all accessor and modifier methods return an Attribute instance, which defines how to access and modify the attribute.

When calling the mutator method on a property, the set parameter will be used. For simplicity, we just used the strtolower function, which converts the post title to lowercase before saving it to the database.

This way you can create mutation methods on all columns of the table. Next, let's look at accessor methods.

Accessor methods

If you use variables to change the data before saving it to the database, accessor methods are used to change the data after getting it from the database. To define an accessor method, you need to provide the get parameter when defining the property.

Let's take a look at the accessor methods.

protected function name(): Attribute
{
    return Attribute::make(
        get: fn ($value) => ucfirst($value),
        #set: fn ($value) => strtolower($value),
    );
}
Copy after login

After getting the value of the name attribute from the database, the get parameter will be called. In our case, we just used the ucfirst method to change the post title.

So far we have just created the assignor and accessor methods, but we will test them in the next sections.

The role of mutator

Let's create a controller in app/Http/Controllers/MutatorController.php so that we can test the mutator method we created in the previous section.

<?php
// app/Http/Controllers/MutatorController.php
namespace App\Http\Controllers;
 
use App\Post;
use App\Http\Controllers\Controller;
 
class MutatorController extends Controller
{
    public function index()
    {
        // create a new post object
        $post = new Post;
        $post->name = 'Post Title';
        $post->save();
    }
}
Copy after login

Additionally, you will need to create an associated route in the routes/web.php file to access the mutator controller.

Route::get('mutator/index', 'MutatorController@index');
Copy after login

In the index method, we create a new post using the Post model. It should set the value of the name column to the post title value because we used the strtolower function in the corresponding mutator method.

Accessors in operation

To see the accessor in action, let's go ahead and create a controller file with the following content app/Http/Controllers/AccessorController.php:

<?php
namespace App\Http\Controllers;
 
use App\Post;
use App\Http\Controllers\Controller;
 
class AccessorController extends Controller
{
    public function index()
    {
        // load post
        $post = Post::find(1);
         
        // check the name property, it should be output of the ucfirst function
        echo $post->name;
        exit;
    }
}
Copy after login

Similarly, you need to use the associated route in the routes/web.php file to access the accessor controller.

Route::get('accessor/index', 'AccessorController@index');
Copy after login

In the index method, we first load the example post using the Post model.

Next, we check the value of the name column, which should start with a capital letter because we have defined an accessor method for that column.

This is how Eloquent mutators and accessors work!

in conclusion

Today, we explored the concepts of modifiers and accessors for the Eloquent ORM in Laravel. It provides a great way to change data before saving it to the database and extracting it from the database.

For those of you just getting started with Laravel or looking to expand your knowledge, website, or application with extensions, we have a variety of content for you to learn from on the Envato Market.

The above is the detailed content of Elegant accessors and modifiers in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!