Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yohannanv's avatar

Laravel 11 Eloquent Query

I am using the following function in Laravel 11 after upgrading the application from Laravel 5.7. However, I am encountering the following error: "message": "Object of class Illuminate\Database\Query\Expression could not be converted to string"

public static function getsavedOccupations($clientId, $savedCipCds) { $cipCodes = array_values($savedCipCds);

// Format the CIP codes for the FIELD function
$formattedCipCodes = implode(',', array_map(function($code) {
    return "'" . $code . "'";
}, $cipCodes));

// Retrieve the occupations from the database
$occupations = DB::table('client_cipcodes')
    ->distinct()
    ->select('id', 'cip_code', 'cip_name', 'web_url')
    ->where('client_id', '=', $clientId)
    ->whereIn('cip_code', $cipCodes)
    ->orderByRaw("FIELD(cip_code, $formattedCipCodes)")
    ->get()
    ->toArray();

return $occupations;

}

How can I resolve this error?

0 likes
11 replies
rodrigo.pedra's avatar

Are you sure the error is triggered by this query?

I created a sample project with your code, and it runs fine.

<?php // routes/console.php

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

Artisan::command('app:run', function () {
    $clientId = 1;

    $cipCodes = array_values([1, 2, 3]);

    // Format the CIP codes for the FIELD function
    $formattedCipCodes = implode(',', array_map(function ($code) {
        return "'" . $code . "'";
    }, $cipCodes));

    // Retrieve the occupations from the database
    $occupations = DB::table('client_cipcodes')
        ->distinct()
        ->select('id', 'cip_code', 'cip_name', 'web_url')
        ->where('client_id', '=', $clientId)
        ->whereIn('cip_code', $cipCodes)
        ->orderByRaw("FIELD(cip_code, $formattedCipCodes)")
        ->get()
        ->toArray();

    \dd($occupations);
});
<?php // database/migrations/0002_01_01_000002_create_client_cipcodes_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('client_cipcodes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('client_id');
            $table->unsignedInteger('cip_code');
            $table->string('cip_name')->nullable();
            $table->string('web_url')->nullable();

            $table->timestamps();
        });

        DB::table('client_cipcodes')->insert([
            [
                'client_id' => 1,
                'cip_code' => 1,
                'cip_name' => 'A',
                'web_url' => 'https://example.com/',
            ],
            [
                'client_id' => 1,
                'cip_code' => 2,
                'cip_name' => 'B',
                'web_url' => 'https://example.com/',
            ],
            [
                'client_id' => 1,
                'cip_code' => 3,
                'cip_name' => 'C',
                'web_url' => 'https://example.com/',
            ],
            [
                'client_id' => 2,
                'cip_code' => 1,
                'cip_name' => 'A',
                'web_url' => 'https://example.com/',
            ],
            [
                'client_id' => 2,
                'cip_code' => 2,
                'cip_name' => 'B',
                'web_url' => 'https://example.com/',
            ],
        ]);
    }
};

Results:

$ php artisan app:run
array:3 [
  0 => {#514
    +"id": 1
    +"cip_code": 1
    +"cip_name": "A"
    +"web_url": "https://example.com/"
  }
  1 => {#517
    +"id": 2
    +"cip_code": 2
    +"cip_name": "B"
    +"web_url": "https://example.com/"
  }
  2 => {#518
    +"id": 3
    +"cip_code": 3
    +"cip_name": "C"
    +"web_url": "https://example.com/"
  }
] // routes/console.php:24

The only thing I can think of if is any of the codes on the $cipCodes array is an Expression object.

In that case, you can change your array_map call to:

use Illuminate\Database\Query\Expression;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

// ...

    // Format the CIP codes for the FIELD function
    $formattedCipCodes = implode(',', array_map(function ($code) {
        return match ($code instanceof Expression) {
            true => "'" . $code->getValue(DB::connection()->getQueryGrammar()) . "'",
            default => "'" . $code . "'",
        };
    }, $cipCodes));
yohannanv's avatar

Hi,

I have modified my function like below and getting the same error. I assume its a compatibility issue with Laravel 11.0 and Maria DB 10.11. If I run the above code in standalone PHP code with PDO and I am getting the results.

public static function getsavedOccupations($clientId, $savedCipCds) { // Format the CIP codes for the FIELD function $formattedCipCodes = implode(',', array_map(function ($code) { return match ($code instanceof Expression) { true => "'" . $code->getValue(DB::connection()->getQueryGrammar()) . "'", default => "'" . $code . "'", }; }, $savedCipCds));

// Enable query log for debugging
// DB::enableQueryLog();

$occupations = DB::table('client_cipcodes')
    ->distinct()
    ->select('id', 'cip_code', 'cip_name', 'web_url')
    ->where('client_id', '=', $clientId)
    ->whereIn('id', $savedCipCds)
    ->orderByRaw("FIELD(cip_name, $formattedCipCodes)")
    ->get()
    ->toArray();

// Debugging the query
// dd(DB::getQueryLog()); exit;

return $occupations;

}

yohannanv's avatar

After modifying the code like above I am getting this error.

message: "Object of class Illuminate\Database\Query\Expression could not be converted to string",…} exception : "Error" file : "/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php"

What is the issue? I have tried different ways and getting the cipcode values correct. Still getting this issue. Is there any setting I need to do in PHP and MariaDB settings?

Snapey's avatar

dump $savedCipCds and check exactly what it contains. It should be a simple array of IDs.

yohannanv's avatar

public static function getsavedOccupations($clientId, $savedCipCds) { // Format the CIP codes for the FIELD function $formattedCipCodes = implode(',', array_map(function ($code) { return match ($code instanceof Expression) { true => "'" . $code->getValue(DB::connection()->getQueryGrammar()) . "'", default => "'" . $code . "'", }; }, $savedCipCds));

echo "<PRE>";
print_r($savedCipCds);
echo "</PRE>";
echo "<PRE>";
print_r($formattedCipCodes);
echo "</PRE>";exit;


// Enable query log for debugging
// DB::enableQueryLog();

$occupations = DB::table('client_cipcodes')
    ->distinct()
    ->select('id', 'cip_code', 'cip_name', 'web_url')
    ->where('client_id', '=', $clientId)
    ->whereIn('id', $savedCipCds)
    ->orderByRaw("FIELD(cip_name, $formattedCipCodes)")
    ->get()
    ->toArray();

// Debugging the query
// dd(DB::getQueryLog()); exit;

return $occupations;

}

I have printed the values and its like below.

$savedCipCds = Array ( [0] => 367399 [1] => 366981 [2] => 366573 [3] => 366151 [4] => 365875 [5] => 367334 [6] => 366583 [7] => 366940 [8] => 5401141 [9] => 5466772 [10] => 5671944 [11] => 5671592 [12] => 5835157 [13] => 5835776 [14] => 5835171 [15] => 5835431 [16] => 5835260 [17] => 5835556 [18] => 5835447 [19] => 5835452 [20] => 5835246 [21] => 5835495 [22] => 5835617 [23] => 7447348 ) $formattedCipCodes = '367399','366981','366573','366151','365875','367334','366583','366940','5401141','5466772','5671944','5671592','5835157','5835776','5835171','5835431','5835260','5835556','5835447','5835452','5835246','5835495','5835617','7447348';

Snapey's avatar

Please learn to format your code blocks

Snapey's avatar

and if you leave out the order by?

yohannanv's avatar
$occupations = DB::table('client_cipcodes')
        ->distinct()
        ->select('id', 'cip_code', 'cip_name', 'web_url')
        ->where('client_id', '=', $clientId)
        ->whereIn('id', $savedCipCds)
        //->orderByRaw("FIELD(cip_name, $formattedCipCodes)")
        ->get()
        ->toArray(); 

I modified the above code and run this command

composer dump-autoload

Still getting the same error - message: "Object of class Illuminate\Database\Query\Expression could not be converted to string",…} exception : "Error" file : "/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php" line : 938

yohannanv's avatar

The issue was with the $savedCipCds generation function, which was similar to this code. I applied the same logic there, and the issue has been resolved.

Please or to participate in this conversation.