Mahmoud Khosravi
Mahmoud Khosravi

Reputation: 496

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string laravel 7

I have been trying to debug a problem for the past two days, my code, as follows, is first attempting to retrieve the category by its:

Controller

public function index(Request $request)
{
    $stats = [
        'done' => UserTransaction::where('status', UserTransaction::STATUS['done']),
        'canceled' => UserTransaction::where('status', UserTransaction::STATUS['canceled']),
        'waiting_payment' => UserTransaction::where('status', UserTransaction::STATUS['waiting_payment']),
    ];
    return view('admin.transaction.index', compact('stats'));
}

UserTransaction.php

const STATUS = [
    'done' => 'done',
    'canceled' => 'canceled',
    'waiting_payment' => 'waiting_payment',
];

index.blade.php

<h3 class="info">{!! $stats['done'] !!}</h3>

I see this error

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string (View: C:\xampp3\htdocs\projects\webafra\tessa-admin\Modules\Transaction\Resources\views\admin\index.blade.php)

Upvotes: 0

Views: 268

Answers (2)

John Lobo
John Lobo

Reputation: 15319

I think you need to modify your query

  $stats = [
        'done' => UserTransaction::where('status', UserTransaction::STATUS['done'])->first(),
        'canceled' => UserTransaction::where('status', UserTransaction::STATUS['canceled'])->first(),
        'waiting_payment' => UserTransaction::where('status', UserTransaction::STATUS['waiting_payment'])->first(),
    ];

also make sure $stats['done'] return object.you should fetch like $stats['done']->status

also you can improve your code a bit

create a scope method in your model

  public function scopeStatus($query,$status){
    
    $query->where('status',$status);
    
    }

then you can access like this

   UserTransaction::status(UserTransaction::STATUS['done'])->first();

Also you can keep status array in constant separately in config or you have to create each scope for each status

Updated Since you are looking for count of the status

  $stats = [
        'done' => UserTransaction::where('status', UserTransaction::STATUS['done'])->count(),
        'canceled' => UserTransaction::where('status', UserTransaction::STATUS['canceled'])->count(),
        'waiting_payment' => UserTransaction::where('status', UserTransaction::STATUS['waiting_payment'])->count(),
    ]; 

Upvotes: 1

Alpy
Alpy

Reputation: 789

Your $stats is actually an Object of the UserTransaction query and this cannot displayed in the blade as a String.

Debug the stats Object with:

<h3 class="info">{!! dd($stats['done']) !!}</h3>

and see how the Object is displayed

Upvotes: 0

Related Questions