Laravel use of concat with pluck method - php

I am using Laravel.5.3 and below is my query
$ProjectManagers = Employees::where("designation" , 1)
->pluck(DB::raw('CONCAT(first_name," ",last_name) AS name'),'id');
which throws an error that
Illegal offset type in isset or empty
May i know if this is the correct method ?
if i dont use contact and use like
$ProjectManagers = Employees::where("designation" , 1)->pluck('first_name','id');
which is working correct and giving me result
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[8] => Punit
)
)
Expected Result :
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[8] => Punit Gajjar
)
)
where first name and last name are concatenated.

The most elegant solution is to create an accessor.
Open your Employees class (model) and add an accessor function:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
After that, just simply use:
$ProjectManagers = Employees::where('designation', 1)->get()->pluck('full_name', 'id');

Try changing the eloquent query to:
$ProjectManagers = Employees::select(
DB::raw("CONCAT(first_name,' ',last_name) AS name"),'id')
->where('designation', 1)
->pluck('name', 'id');

if your column is nullable then you should try this
convert the NULL values with empty string by COALESCE
$ProjectManagers = Employees::select(
DB::raw("CONCAT(COALESCE(`first_name`,''),' ',COALESCE(`last_name`,'')) AS name"),'id')
->where('designation', 1)
->pluck('name', 'id')
->toArray();

I also faced a problem like that with join query here is the solution of my problem
$studentDegree = Student::leftJoin('degree','degree.student_id','=','student.id')
->select(
DB::raw("CONCAT(student.name,'-',degree.name) AS name_degree"),
'student.id'
)->lists('name_degree','id');

Related

How to Use WhereIn Query in Laravel 8

Controller
public function detail(Peserta $peserta)
{
// get konfirmasi_id
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id')->get();
$payments = BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();
// dd($payments);
$tagihan = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
}
I want to display data from BankSettlement based on konfirmasi_id. Here I try to use WhereIn Query like this, but still error "Property [id] does not exist on this collection instance.".
$konfirmasi has data like the image above.
What is the correct way to display data from BankSettlement based on konfirmasi_id ? Thankyou
Try this changes:
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->pluck('id')->toArray();
$payments = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();
This is the wrong way to change a collection to array.
$payments=BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();
You should do this
public function detail(Peserta $peserta)
{
// get konfirmasi_id
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)
->select('id')
->get()
->pluck('id')
->toArray(); //This will return an array of ids
$payments = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();
// dd($payments);
$tagihan = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
}
Edit:
Read Laravel Collections|Pluck
If you do not have to reuse the result of $konfirmasi then it would be better to use subquery. Writing a subquery is optimized way. if you write two different query then there will be two seperate database connection request.
Laravel subquery
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id');
$payments = BankSettlement::whereIn('konfirmasi_id', $konfirmasi )->get();

How to solve "Cannot use object of type stdClass as array" error in custom query in laravel?

I am using laravel 5 and I want to show the result data of my query in my blade view. But I've got an error :
Cannot use object of type stdClass as array
It seems ok if I used the query builder from laravel like :
$surat = new Surat();
$surats = $surat->select('name', 'age', 'sex')->get();
$data_surat = ['surat' => $surats];
return view('profile', $data_surat);
But, if I am using custom query like the query below, I've got the error.
$surats = DB::select( DB::raw("SELECT `name`, `age`, `sex` from `surat`") );
$data_surat = ['surat' => $surats];
return view('profile', $data_surat);`
Do you know how to solve it? I need to use a custum query tho.

Eloquent ORM laravel 5 Get Array of ids

I'm using Eloquent ORM laravel 5.1, and I want to return an array of ids greater than 0, my model is called test.
I have tried :
$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();
It returns :
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )
But I want the result to be in simple array like this:
Array ( 1,2 )
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE:
If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
UPDATE: For versions < 5.2
You could use lists() :
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case format, e.g Test.
You could also use get() :
test::where('id' ,'>' ,0)->get('id');
From a Collection, another way you could do it would be:
$collection->pluck('id')->toArray()
This will return an indexed array, perfectly usable by laravel in a whereIn() query, for instance.
The correct answer to that is the method lists, it's very simple like this:
$test=test::select('id')->where('id' ,'>' ,0)->lists('id');
Regards!
You can use all() method instead of toArray() method (see more: laravel documentation):
test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array
If you need a string, you can use without toArray() attachment:
test::where('id' ,'>' ,0)->pluck('id'); //returns string
Just an extra info, if you are using DB:
DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();
And if using Eloquent model:
test::where('id', '>', 0)->lists('id')->toArray();
A simple way to get an array with the model IDs from a collection:
$test = test::select('id')->where('id' ,'>' ,0)->get('id')->modelKeys();
Available since Laravel 5.5: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
Although you have marked the Answer, This is a much simpler approach
App\User::pluck('id')->toArray()
In Laravel 8 this works for me
$arr = SomeModel::where("field", value)->get()->toArray();

How to Select Certain Fields in Laravel Eloquent?

How to Do following Query in Laravel Eloquent?
SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"
I have tried following
CategoryModel::where('catType', '=', 'Root')
->lists('catName', 'catID', 'imgPath');
but its return only two fields.
Array ( [7] => Category 1 )
lists() turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select() but then you will get a collection of models not just an array.
$categories = CategoryModel::select('catID', 'catName', 'imgPath')
->where('catType', '=', 'Root')
->get();
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
If you want to get certain columns then You can use one of the two method get() or all()
but the syntax is different for both, get() method takes array as argument and all() method takes string or array both as argument:
Model::all('field1','field2') with string as arguments
CategoryModel::all('catName', 'catID', 'imgPath')->where('catType','Root');
Model::all(['field1','field2']) with array as arguments
CategoryModel::all(['catName', 'catID', 'imgPath'])->where('catType','Root');
Model::get(['field1','field2'])
CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
From laravel version 5.3^ lists() is deprecated and function pluck() is used instead.
pluck() returns a collection and if you need a simple array just prepend ->toArray() to it.

codeigniter, result() vs. result_array()

I use both result() and result_array().
Usually i like to get my result as array thats why i use result_array() mostly..
But i want to know which is the better approach that i should follow,
Which one of them is more efficient to use in regards to performance?
Here is the Example i am talking about in codeigniter queries
$query = $this->db->get();
$result = $query->result_array();
or is this should be the better approach??
$query = $this->db->get();
$result = $query->result();
also right now i am using result_array in my generic model.
Result has an optional $type parameter which decides what type of result is returned. By default ($type = "object"), it returns an object (result_object()). It can be set to "array", then it will return an array of result, that being equivalent of caling result_array(). The third version accepts a custom class to use as a result object.
The code from CodeIgniter:
/**
* Query result. Acts as a wrapper function for the following functions.
*
* #param string $type 'object', 'array' or a custom class name
* #return array
*/
public function result($type = 'object')
{
if ($type === 'array')
{
return $this->result_array();
}
elseif ($type === 'object')
{
return $this->result_object();
}
else
{
return $this->custom_result_object($type);
}
}
Arrays are technically faster, but they are not objects. It depends where do you want to use the result. Most of the time, arrays are sufficient.
for the sake of reference:
// $query->result_object() === $query->result()
// returns:
Array ( [0] => stdClass Object ( [col_A] => val_1A , [col_B] => val_1B , ... )
[0] => stdClass Object ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
// $query->result_array() !== $query->result()
// returns:
Array ( [0] => Array ( [col_A] => val_1A , [col_B] => val_1B , ... )
[1] => Array ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
codeigniter docs for result(), and result_array()
result_array() is faster,
result() is easier
result() returns Object type data.
.
.
.
result_array() returns Associative Array type data.
Returning pure array is slightly faster than returning an array of objects.
result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance. There is very little difference in speed though.
result_array() returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance.
in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON

Categories