Areza
Areza

Reputation: 721

Default Attribute With random Values in laravel model

In my laravel project, I want set a random default value for each new created record.

According of this Doc, I try this:

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    protected $fillable = [
       'access_token'
    ];

    protected $attributes = [
        'access_token' => str::uuid()
    ];
}

But I get error for protected $attributes line

"Constant expression contains invalid operations"

Upvotes: 4

Views: 3961

Answers (3)

Mozammil
Mozammil

Reputation: 8750

This is because properties cannot contain expressions that they cannot evaluate at compile time. From the official documentation.

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

Another way of doing this would be through model events. In your User model's boot() method, you can hook into the Creating event. If this method does not exist, create it.

public static function boot()
{
    parent::boot();

    static::creating(function($user) {
        $user->access_token = (string) Str::uuid();
    });
}

Upvotes: 6

Anton Shever
Anton Shever

Reputation: 31

protected $attributes = [
    'access_token' => ''
];

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->attributes['access_token'] = Str::uuid();
}

In php, it is impossible to call a function from a property

Upvotes: 3

Francis Kisiara
Francis Kisiara

Reputation: 325

The problem is arising from the way in which you are calling the uuid function.

Since it is static, you will need to access it using;

Str::uuid()

And this will return an object, so in order to get a string out of it, you will have to cast the result.

(string) Str::uuid()

Therefore essentially, your attributes property should be;

protected $attributes = [
    'access_token' => (string) Str::uuid()
];

You can have a look at the docs

Upvotes: -1

Related Questions