Laravel pluck but combining first name + last name for select - laravel

Using select2 with a Laravel / Vue project and need to return JSON in the following format:
[
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' }
]
In Laravel I know I can use pluck to create my list data e.g. for customers:
$customers = Customer::pluck('id', 'first_name');
But Want to return the id and first name + last name as a single name.
How can I do this?

Have you tried using Accessors?
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
I have not tested it but this could work:
add this to your Customer Eloquent Model:
public function getFullNameAttribute()
{
return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}
and then try:
UPDATED pluck on accessor will only work on a collection. If you try Customer::pluck('id', 'full_name') it will not work since there is no db column named full_name, therefore you must use Customer::all()->pluck('full_name', 'id')
$customers = Customer::all()->pluck('full_name', 'id');
as a side note, for performance it is probably better to do Customer::all(['id', 'first_name', 'last_name'])->pluck(...) so that we don't pull unnecessary columns from the db.
Hope this helps.
Updated Date:- 26th Aug, 2021
If we use computed Attribute accessor functionality, then mind it one important thing...
Laravel Accessor functionality works after the Data fetched from DataBase. So we have to declare "pluck(accessorName)" at the end of Query....
For Example:-
Wrong Methods:-
$data = Model::pluck('full_name','id)->get();
$data = Model::pluck('full_name','id)->all();
in above two queries if you does not have full_name field in DataTable you will get Unknown column error
Right Methods:-
$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');
in above two queries it will works perfectly even if you doesn't have full_name field in DataTable

You can do it like this,
$customers = DB::table('customers')->select("id", "CONCAT(firstname,' ',lastname) as fullname")->get();
or you also do like this,
$customers = DB::table('customers')->select(DB::raw('CONCAT(firstname,' ',lastname) as fullname, id'))->get();
or with PHP way,
$fullname = $customers->firstname. " " .$customers->lastname;

Set this in the User model
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Then make sure you add this too
protected $appends = ['full_name'];

For me it worked
\DB::table("admin as c")->select(\DB::raw("CONCAT(FirstName, ' ', LastName) AS FIRSTNAME"),"c.AdminID")->pluck("FIRSTNAME","AdminID");

Use this code. Hope it will work. And I solve this problem using this code
User::select(DB::raw("CONCAT(first_name, ' ', last_name) AS full_name"),"id")->pluck("full_name","id");

User Model :
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
Get query will result in collection :
$agents = User::whereId($agent->id)->get()->pluck('full_name', 'id');
Inorder to convert variable from objects to array :
$agents = json_decode(json_encode($agents), true);
It worked for me.Enjoy.

/**
* Get the full name of the user.
*
* #return string
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
and use this pluck
User::all()->sortBy('id')->pluck('full_name', 'id')
like this
public static function list()
{
return Cache::tags('usersCustomers')->rememberForever(md5('usersCustomers.list:' . locale()), function () {
return self::all()->sortBy('id')->pluck('full_name', 'id');
});
}

** Use this code. Hope it will work. And I solve this problem using this code**
User::select(DB::raw("CONCAT(first_name, ' ', last_name) AS
full_name"),"id")->pluck("full_name","id");

Related

Laravel8 attribute or appends in query where

I want to reach the record
if in model User
class User extends Model {
protected $fillable = ['last_name','first_name'];
protected $appends = [
'full_name',
];
public function getFullNameAttribute(): string
{
return $this->first_name . ' ' . $this->last_name;
}
}
in request
full_name = 'John Johans';
How to get database record if
User::query()->where('full_name',$request->full_name)
If I use this record the answer will be an error that full_name does not exist in the database
I would like to use "where" for "appends"
User::query()->where(**MY ATTRIBUTE**,$request)->first()
it is possible ?
2 Options:
Use CONCAT in your WHERE clause
User::query()
->whereRaw('CONCAT(first_name, " ", last_name) = "?"', [$request->full_name])
->get();
Get all the users and then filter in the resulting Collection.
User::cursor()
->filter(function ($user) use ($request) {
return $user->full_name == $request->full_name;
})
->collect();
User::cursor()
->filter(fn($user) => $user->full_name == $request->full_name)
->collect();
Letting SQL do the filtering (Option 1) is probably the better choice.

Query builder didn't find data when using %

I'm trying to use query builder in controller using laravel, and i don't understand but the query didn't find the data.
Here's the code:
public function index()
{
$data = downloads::all();
if(request('searchName')){
$data = $data->where('fileName','like','%'.request('searchName').'%'); //Here's the problem
return view('download', compact('data'));
}
else{
return view('download', compact('data'));
}
}
i already tried dd(request('searchName')) and it display the input that i give, so there's no problem here
when I'm using $data->where('fileName','like','%'.request('searchName').'%') there's no data shown
i don't think that i misspell the fileName because when I'm using $data->where('fileName','like',request('searchName')) and it worked and display the file, but the fileName must be exactly the same as the inputed searchName, and of course what i wanted is not this
even when I'm using dd('%'.request('searchName').'%'); it will display "%*searchName*%" that's why i so confused when it didn't work when I'm using $data->where('fileName','like','%'.request('searchName').'%');
I even using SELECT * FROM *tables* WHERE fileName LIKE '%p%'; in SQL Workbench and it worked perfectly fine
Any suggestion of what should i do? Thank you
This looks odd. Why are you filtering the collection instead of adding the where conditional in your query?
Imagine you have thousands of download records but the where condition just match with a few ones, you will be fetching everything just for showing some of them.
IMO, a better approach should be
public function index(Request $request)
{
$data = downloads::
when($request->has('searchName'), function($query) use ($request){
$query->where('fileName','like','%'.$request->searchName.'%');
})
->get();
return view('download', compact('data'));
}
all() is static method not query builder.If you see internal of all() code then its calling get method
/**
* Get all of the models from the database.
*
* #param array|mixed $columns
* #return \Illuminate\Database\Eloquent\Collection|static[]
*/
public static function all($columns = ['*'])
{
return static::query()->get(
is_array($columns) ? $columns : func_get_args()
);
}
There are few ways to solve this .
public function index()
{
$downloads = downloads::query();
if(!empty(request('searchName'))){
$downloads->where('fileName','like','%'.request('searchName').'%');
}
$data=$downloads->get();
return view('download', compact('data'));
}
or
public function index()
{
$data = downloads::when(!empty(request('searchName')),function($query){
$query->where('fileName','like','%'.request('searchName').'%');
})->get();
return view('download', compact('data'));
}
You are trying to apply your querystring with like in a collection. In a collection, you can use the filter($callback_function) method to select elements in the collection. Pass a callback function that returns true for each element to be returned.
In your case, you can use the stristr() function to emulate a LIKE operator, something like this:
collect($data)->filter(function ($item) use ($searchName) {
return false !== stristr($item->fileName, $searchName);
});

How to get data HasMany() using WhereHas in Laravel

I want to get data from my table " Package " by using its model " Package "
and in this model " Package " it have a HasMany() named histories() relation to model " History "
so i want to only get data that have histories
here is my controller
public function getIncomeMPW(Request $request)
{
if ($request->expectsJson()) {
$this->getSearch($request);
$query = new Package();
$query->with(['histories', 'items', 'items.prices', 'origin_regency', 'origin_district', 'origin_sub_district', 'destination_regency', 'destination_district', 'destination_sub_district', 'code', 'attachments']);
$query->whereHas('histories', function (Builder $query) {
$query->whereNotNull('partner_id');
});
$query->orderBy('created_at', 'desc');
return (new Response(Response::RC_SUCCESS, $this->query->paginate(request('per_page', 15))))->json();
}
}
here is my Package model relation histories HasMany()
public function histories(): HasMany
{
return $this->hasMany(History::class, 'package_id', 'id');
}
and last here is my response that showing right now
i already try using whereHas(), Has(), whereDoesntHave(), and its seems like there is no impact on my response, can anyone help me please ?
In your response you simply access a different query as it seems.
return (new Response(Response::RC_SUCCESS, $this->query->paginate(request('per_page', 15))))->json();
Uses $this->query
While
$query = new Package();
$query->with(['histories', 'items', 'items.prices', 'origin_regency', 'origin_district', 'origin_sub_district', 'destination_regency', 'destination_district', 'destination_sub_district', 'code', 'attachments']);
$query->whereHas('histories', function (Builder $query) {
$query->whereNotNull('partner_id');
});
$query->orderBy('created_at', 'desc');
Defines a $query without $this. I'd expect your $this->getSearch($request); to define $this->query (as the function is not posted in the question, i cannot tell). So either remove $this in your response - or change everything to $this and ensure to now overwrite it in the first line.
Quickfix should be
return (new Response(Response::RC_SUCCESS, $query->paginate(request('per_page', 15))))->json();
UPDATE:
Quick answer: Change
return (new Response(Response::RC_SUCCESS, $this->query->paginate(request('per_page', 15))))->json();
To
return (new Response(Response::RC_SUCCESS, $query->paginate(request('per_page', 15))))->json();
Wwhat whereHas and whereDoesntHave functions do in the backstage is that they make a sub query such as:
Select * from packages where exists (select * from histories where CONDITIONS YOU HAVE MENTIONED)
And the problem here is that when you use with method you eager load table history which adds one extra query that is not related to the first one such as:
Select * from histories where package_id in (1,2,3,4,5,6)
So since we cleared that out, what I suggest you do is that you assign a function to a variable in this way:
$historyFunction = function ($query) {
$query->whereNotNull('partner_id');
};
and than call it in with and in whereHas methods as shown below:
$query->with(['histories' => $historyFunction, otherRelations... ]);
$query->whereHas('histories', $historyFunction);
And what this does is that it tells eloquent: When you eager load Histories relationship add this conditions to the query you are about to make.

whereBetween doesnt exist and i cant apply paginate

I've this method:
public function indexGuest($idAzienda, Request $request){
$companyId = $idAzienda;
$ddts = Ddt::where('company_id',$companyId);
$ddt_urls= Ddt_file_url::all();
if($request->start_date || $request->end_date){
$ddts->whereBetween('created_at',[new Carbon($request->start_date),new Carbon($request->end_date)]);
}
$ddts->paginate(10);
return view('guest.ddt-management')->with('ddts', $ddts)->with('ddt_urls',$ddt_urls)
->with('companyId',$companyId);
}
My start_date and end_date comes in strings like "yyyy-mm-dd".
I've tried to pass it straight to the query and like in the example like a carbon object with no hope!
After executing the query (now only the one without the wherebeeteween clause) i cant apply the method "paginate" to the collection, no error are raised but when i pass it to the view, the "link()" method not work and raise an error again.
where I wrong?
Laravel 5.4
Structure your wheres like this.
public function indexGuest($idAzienda, Request $request) {
[...]
$ddts = Ddt::where('company_id', $companyId)
->where(function($query) use ($request) {
if($s = $request->get("start_date") {
$s_date = Carbon::parse($s)->format("Y-m-d");
$query->whereDate("created_at", ">=", $s_date);
}
if($e = $request->get("end_date") {
$e_date = Carbon::parse($e)->format("Y-m-d");
$query->whereDate("created_at", "<=", $e_date);
}
})
->paginate(10);
[...]
}

codeigniter pass variable from controller to model

simple issue I presume.
My controller is getting the if to display from the url using $this->uri->segment(3). This will always be a single value. I am putting this in an array to pass to the model with:
$customerid = array(
'id' => $this->uri->segment(3)
);
The controller syntax is below:
function confirm_delete_customer()
{
$data['title']="Confirm Customer Deletion";
$customerid=array(
'id'=>$this->uri->segment(3)
);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
I am then trying to access this array value and pass it to my model to process. If I hard code the array into the model it works as per below syntax:
Model - Manual Syntax is:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', array('id'=>43));
return $query->result();
}
if I try replace this with the array from my controller it fails with error:
Undefined variable: customerid
idea of model that I want to get working:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', $customerid);
return $query->result();
}
I have a feeling it is something small. however is this the best way to get a single record from the database in order to output to a view?
Thanks in advance for the assistance.
The best way to do that is:
function confirm_delete_customer()
{
$data=array();
$data['title']="Confirm Customer Deletion";
$customerId = $this->uri->segment(3);
//Prevent SQL injections
if(!is_numeric($customerId) || empty($customerId)) {
show_error("Bad Request");
}
$query = $this->model_master_data->get_customer_records_to_delete($customerId);
if ($query){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
}
and then you can simply call:
function get_customer_records_to_delete($customerId)
{
$query = $this->db->get_where('customers', array('id'=>$customerId));
return $query->result();
}
at your model.
You need to pass the value as an argument to the function so it can access it.
Ex:
get_customer_records_to_delete($customerid)
{
// now $customerid is accessible
$query = ....;
return $……;
}
You should heavily rely on function parameters. Grab the customer id from the controller and send it to the model. Moreover, you can use row() to get a single result from the database.
Controller:
function confirm_delete_customer(){
$data['title']="Confirm Customer Deletion";
$customerid=$this->uri->segment(3);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete( $customerid)) //you are sending customer id as a parameter here
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}}
Model
function get_customer_records_to_delete($customerid)
{
$query = $this->db->get_where('customers', array("id"=>$customerid)); //you are using the customer id sent from the controller here
return $query->row(); //this will return a single row
}
Old thread but the answer is to declare the variable as "public" in the controller (i.e. public $customerid;), in which case it'll be available to your model. In some cases it's probably safer to explicitly pass as an argument. However, when you have several variables, it's useful to have the option to declare them instead.

Resources