Home > database >  Object of class stdClass could not be converted to string ERROR when running laravel query
Object of class stdClass could not be converted to string ERROR when running laravel query

Time:04-04

I am using a query in Laravel, but when I try to dump it shows this error

'Object of class stdClass could not be converted to string'

This is the query ->

 $staff = User::find($id);
        $departments = Department::all();
        $managers = DB::table('users')
            ->where('role', 'manager')
            ->get();

        $staffId = DB:: table('users')
                ->where('id', $id)
                ->select('deptId')
                ->get();
        
    
        $empDept = DB::table('departments')
                ->join('users','users.deptId','=','departments.id')
                ->select('department_name')
                ->where('departments.id', $staffId)
                ->orWhere('users.deptId', '=', 'departments.id')
                ->pluck('departments.department_name')
                ->first();
    
        dd($empDept);

What could the problem be?

CodePudding user response:

You are passing a Collection of stdClass objects to the where method on the query you are building. It is iterating that Collection and trying to use the values as strings but they are stdClass objects which can not be converted to strings. You should be passing a single value to the where condition:

$staffId = $staff->deptId;

Now you are getting the deptId value from the User object you already have instead of querying the table again.

If you really wanted to query the table again you could just ask for the single value instead of the entire record using the value method:

$staffId = DB:: table('users')
    ->where('id', $id)
    ->value('deptId');

CodePudding user response:

I think you need to decode your data first

$code = json_decode($query, true);
  • Related