cannot perform raw query with DB::select(DB::raw()) after updating to laravel 10

5.4k Views Asked by At

after updating to laravel 10, i cant perform raw query like this:

$statement = 'SELECT';
    foreach ($tables = collect(availableTables()) as $name => $table_name) {
        if ($tables->last() == $table_name) {
            $statement .= "( SELECT COUNT(*) FROM $table_name) as {$table_name}";
        }
        else {
            $statement .= "( SELECT COUNT(*) FROM $table_name) as {$table_name}, ";
        }
    }
    $query  = DB::select(DB::raw($statement));

this returns me the following error:

PDO::prepare (): Argument #1 ($query) must be of type string, Illuminate\Database|Query\ Expression given

what should i do to fix this issue

3

There are 3 best solutions below

4
Ron Marsden On BEST ANSWER

You don't need to use DB::raw() inside DB::select():

DB::select("select @@sql_mode");

So, you can just use the following instead:

$query = DB::select($statement);
0
sibi HaSeb On

For Laravel 10 This fixed my problem:

DB::select(DB::raw('select 1')->
getValue(DB::connection()->getQueryGrammar()));
0
Jignesh Joisar On

you need to convert into the string before laravel 10 automatically converted into string now we need to do manually

use Illuminate\Support\Facades\DB;

DB::raw($query)->getValue(DB::getQueryGrammar());

or create a one helper method

if (! function_exists('rawQuery')) {
    function rawQuery($query): string
    {
        return DB::raw($query)->getValue(DB::getQueryGrammar());
    }
}

or create a new facade and extend DB facade here

<?php

namespace App\Facades;

use Illuminate\Support\Facades\DB;

class DBO extends DB
{
    public static function raw($query){
        return parent::raw($query)->getValue(parent::getQueryGrammar());
    }
}

Then add into app/app.php for overwrite db facade

'aliases' => Facade::defaultAliases()->merge([
    'DB' => App\Facades\DBO::class,
])->toArray(),

i m using last way because not need to change any code in the project