skip to Main Content

I have a query

$result = DB::select("SELECT * FROM table_name WHERE id=$id");

I want to get one object, but it returns an array of objects.

I added ->first() to my code as follows:

$result = DB::select("SELECT * FROM table_name WHERE id=$id")->first();

, and I got an error:

Call to a member function first() on array

How to get one object via DB?

2

Answers


  1. Change it to use the query builder instead of the select statement

    $result = DB::table('table_name')->where('id', $id)->first();
    
    Login or Signup to reply.
  2. DB::select method returns an array, and you are trying to call the first() method on an array which is not a valid operation. What that means is $result is an array. You can try this below which will filter based on one specific id in a safer way.

        $result = DB::select("SELECT * FROM table_name WHERE id = ?", [$id]);
    
    // Check if there is a result
    if (!empty($result)) {
        // Get the first element of the array
        $row = $result[0];
    
        // Now you can access the columns of the row like $row->column_name
        $id = $row->id;
        $columnName = $row->column_name;
    
        // access other columns as needed
    } else {
        // Handle the case where no result is found for the given ID
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search