Skip to content
Advertisement

Laravel – Change default value eloquent

Is possible to modify the default value response from Laravel Eloquent?

I have an API and my database has a migration payment. My payment has a column integer status.

$table->integer('status')->default(1);

I want to know if is possible to change the default value with any function to change the Payment->get() response.

For example:

public static $status = [
    1 => "Waiting for payment",
    2 => "In review",
    3 => "Payed",    
];

And automatically call my function:

class Payment extends Model
{
  // ...
  public getStatus() {
    $this->status = $status[$this->status];
  }
}

Advertisement

Answer

Almost; you can change getStatus() to getStatusAttribute(), which is a Laravel Accessor, then simply call:

$payment = Payment::first();
dd($payment->status);
// Or
$payments = Payment::get();
foreach($payments AS $payment){
  dd($payment->status);
}

Instead of outputting 1, 2, etc. this will override the value to 'Waiting for payment', 'In review', etc.

See https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor for full details.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement