Jigar
Jigar

Reputation: 3261

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?

Upvotes: 1

Views: 3136

Answers (3)

dparoli
dparoli

Reputation: 9161

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.

Upvotes: 1

pandesantos
pandesantos

Reputation: 369

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');
 }
}

Upvotes: 0

farooq
farooq

Reputation: 1673

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');
  }
}

Upvotes: 0

Related Questions