2

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];
  }
}
Thiago Valente
  • 673
  • 8
  • 25

1 Answers1

3

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.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • My question was your first answer: ``/** * Get the payment status. * * @param int $value * @return void */ public function getStatusAttribute($value) { return Payment::$status[$value]; } `` – Thiago Valente Nov 01 '19 at 19:11