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
.
JavaScript
x
$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:
JavaScript
public static $status = [
1 => "Waiting for payment",
2 => "In review",
3 => "Payed",
];
And automatically call my function:
JavaScript
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:
JavaScript
$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.