Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 875
Areza Avatar asked Sep 05 '25 03:09

Areza


2 Answers

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();
    });
}
like image 125
Mozammil Avatar answered Sep 07 '25 22:09

Mozammil


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

like image 32
Anton Shever Avatar answered Sep 07 '25 21:09

Anton Shever