简体   繁体   中英

How can i get value from config file and set in $attribute variable in laravel model file?

I want to assign a default value in Laravel model but the value should come from the config file.

I am writing below code but its giving me error

    protected $attributes = [
        'is_generation'    => true,
        'price'       => config('test.MY_PRICE'),
    ];

it's showing me an error like Constant expression contains invalid operations

How can I get value from config file and set in $attribute variable in Laravel model file?

You can use the saving model event by adding this code to your Eloquent Model :

protected static function boot()
{    
    // sets default values on saving
    static::saving(function ($model) {
        $model->price = $model->price ?? config('test.MY_PRICE');
    });
    parent::boot();
}

With this code in place, if the field price is null , it will have assigned a value from the config key just a moment before saving the Model in the database.

BTW you can change the check like if it's an empty string or less then a number and so on, this is only an example.

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.

The only way you can make this work is :-

<?php

namespace App;

class Amazon
{
  protected $serviceURL;

  public function __construct()
  {
    $this->serviceURL = config('api.amazon.service_url');
  }
}

You can use attribute mutator as explained here: https://laravel.com/docs/5.8/eloquent-mutators#defining-a-mutator

Class Example{

 public function setPriceAttribute(){
    return $this->attributes['price'] = config('test.MY_PRICE');
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM