DevBlog

Coding my way

1 year ago in PHP, Laravel · 1 MIN READ

Dynamic Attributes for Eloquent models

Have you ever wanted to create that URL for your post in the model with storing only the slug? Or do some calculation based on your stored data?

Well, here's the solution!

This is your average Laravel model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

First, we will add the custom attribute to our list, like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['url'];
}

This is necessary for the model's toArray() and toJson() methods. Once this is set up, well add an Accessor for our new attribute:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['url'];

    /**
     * @return string
     */
    public function getUrlAttribute() {
        return route('post',[$this->attributes['slug']]);
    }
}

And that's it! You can add almost any kind of logic to the models this way, but be aware that the models should only provide data for your application, not run it!

···

Miklós Galicz

I'm a hobbyist who managed to become a professional web developer who specializes in Laravel and Vue.js, also the Spice must flow.
comments powered by Disqus


© 2017 DevBlog