4

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

arya_la
  • 399
  • 2
  • 10

3 Answers3

8

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);
Ron Marsden
  • 124
  • 2
  • 1
    Thanks @Ron Marsden, is this change available somewhere on the Laravel docs? – Leutecia Apr 18 '23 at 18:23
  • @Leutecia it's not a change - this has been the way in Laravel since at least 6.x, perhaps earlier. See "[Running A Select Query](https://laravel.com/docs/10.x/database#running-a-select-query)" on the documentation. – Ron Marsden Apr 20 '23 at 11:39
  • 1
    then how come it doesn't show any error on laravel 8? – Leutecia Apr 24 '23 at 06:50
  • 1
    @Leutecia There's no error in previous Laravel versions, because DB::raw was only recently modified, as it's documented [in the upgrade guide](https://laravel.com/docs/10.x/upgrade#database-expressions). – Szezs May 26 '23 at 17:09
0

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

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
-1

For Laravel 10 This fixed my problem:

DB::select(DB::raw('select 1')->
getValue(DB::connection()->getQueryGrammar()));