I want to get response with type_name property, without adding new field in the table
{
"status": 200,
"message": "OK",
"data": {
"id": 23,
"uuid": "9b1d33f9-0e44-4161-9936-ec41309697a5",
"sender_id": null,
"receiver_id": 2,
"type": 0,
"coin": 200,
"balance": 27000,
"description": "Topup 200 coin",
"type_name": "Topup"
}
Therefore I tried to create a method named typeName() inside the CoinTransaction model, in the hope that the method can be called via with() method like that:
$transaction = CoinTransaction::create([
'receiver_id' => auth()->user()->id,
'coin' => $request->coin,
'balance' => $predefineCoin->balance ?? 1000,
'type' => 0,
'description' => $request->description
]);
$transaction = CoinTransaction::with(['typeName'])->find($transaction->id);
But it's return an error:
Error: Call to a member function addEagerConstraints() on string...
In my CoinTransaction model
class CoinTransaction extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function sender() {
return $this->belongsTo(User::class, 'sender_id');
}
public function receiver() {
return $this->belongsTo(User::class, 'receiver_id');
}
public function typeName() {
$typeName = null;
switch($this->type){
case 0: $typeName = 'Topup'; break;
default: $typeName = 'Unknown';
}
return $typeName;
}
}
CodePudding user response:
typeName
is not relationship method
so you have typeName()
like below
$coin=CoinTransaction::find($transaction->id);
dd($coin->typeName());
or
To add type_name
attribute to existing response ,you can use Mutators
Ref :https://laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutators
So add below property and method in CoinTransaction
protected $appends = ['type_name'];
and method
public function getTypeNameAttribute()
{
$typeName = null;
switch($this->type){
case 0: $typeName = 'Topup'; break;
default: $typeName = 'Unknown';
}
return $typeName;
}
so in controller
$transaction = CoinTransaction::find($transaction->id);