sumit
sumit

Reputation: 15464

Weird behaviour in laravel eloquent pluck with raw concat

I had the following ORM which was working

$timezones = DB::table('timezones')->pluck(DB::Raw('concat_ws(" ",label,name) as name'), 'id');

I converted it to

$timezones = Timezone::pluck(DB::Raw('concat_ws(" ",label,name) as name'), 'id');

and got the error like below

ErrorException in Str.php line 432:
Illegal offset type in isset or empty

Model is pretty simple like below

class Timezone extends Model
{

     protected $table = 'timezones';
     protected $connection = 'mysql';

}

Upvotes: 1

Views: 1992

Answers (2)

Ravi Gehlot
Ravi Gehlot

Reputation: 1139

One other way to achieve the same results without having to use DB::raw and MySQL's concat_ws is to use Laravel's Accessors. So for example:

On your Timezone model, create an accessor method like this:

public function getLabelAttribute($value)
{
    return $value . ' ' . $this->name;
}

Then you can retrieve that by doing this:

$timezone = Timezone::first();
$timezone->label;

Upvotes: 1

Sagar Gautam
Sagar Gautam

Reputation: 9359

I think, Your raw query inside pluck refers to an object. So, when to try to get an element with index as object error has been displayed.

You should change your query to something like this:

$timezones = Timezone::select(DB::Raw('concat_ws(" ",label,name) as name'), 'id')->pluck('name','id');

This will work. Hope it will help

Upvotes: 5

Related Questions