Laravel distinct query and object to array conversion is not working - php

I want to show unique location names and ids and also i want it as array, if i didint use groupBy it will works and showing data as object. My requiremnt is to retrive it as unique array and its not working.
I dont know what is the error in code
public function showClinicLocations($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
$locationservices = Service::select('services.serviceName as servicename','locations.locationID as locid','locations.locationName as locname')
->groupBy('locid')
->join('location_services', 'location_services.serviceID', '=', 'services.serviceID')
->join('locations', 'locations.locationID', '=', 'location_services.locationID')
->join('clinics', 'clinics.clinicID', '=', 'locations.clinicID')
->where('clinics.clinicID','=',$id)
->get();
echo $locationservices;
die();
// $locationservices = json_encode(array_unique($locationservices));
return view('clinic.locations')->with(['locations' => $locations ,'clinic'=>$clinic , 'services'=> $locationservices]);
}
Can you please help me
I have uploaded output
If there is multiple same loc id only one loc id should be shown

Related

Laravel select missing columns

Objective
I'm trying to select some columns from a multiple inner join query.
I have a model called Item and this model belongs to the other three Produto, Unidadeand Marca
Problem
I'm not getting the full result declared on my query. Only some columns are being shown.
What I tried
I have already tried to put everything in one ->select() , but I had the same issue. I've checked the relations configuration is working in other part of the code
Result Obtained
Only the columns from first and the last addSelect() are being shown.
var_dump() output
Code
public function download()
{
$item = new Item;
// $data = $item->query()
$data = DB::table('items')
->join('produtos', 'items.produto_id', '=', 'produtos.id')
->join('unidades', 'items.unidade_id', '=', 'unidades.id')
->join('marcas', 'items.marca_id', '=', 'marcas.id')
->select('items.codigo','items.nome')
->addSelect('items.metrica_cod', 'items.metrica')
->addSelect('produtos.codigo', 'produtos.nome')
->addSelect('unidades.codigo', 'unidades.nome')
->addSelect('marcas.codigo', 'marcas.nome')
->get();
var_dump($data);
}

Laravel - add key/value to response if ids are the same

I have a contents table with a lot of contents created by different users… I’m trying to verify if a content is created by the user that is logged in and then add a new key value pair to the response, so if the content was created by user_id 1 and I’m user 1 then the response has a field like isOwn : 1 on the content object that is his own, but nothing if the content was created by someone else.
this is the criteria I have:
$query = $model->select('contents.*', 'status_types.name as status', 'content_types.name as content_type')
->join('status_types', 'status_types.id', '=', 'contents.status_type_id')
->join('content_types', 'content_types.id', '=', 'contents.content_type_id')
->with('platforms')
->with('classifications')
->withCount(['favorite' => function ($q) {
$q->where('user_id', '=', $this->request->user()->getIdentifier());
}])
->withCount('likes')
->inRandomOrder();
return $query;
I've tried to use when and whereExist but this return me only the ones created by the user, not if the condition is true.
Any ideas? thanks in advance.
You need to join on the model and make a where for the total query:
$query = $model->select('contents.*', 'status_types.name as status', 'content_types.name as content_type')
->join('status_types', 'status_types.id', '=', 'contents.status_type_id')
->join('content_types', 'content_types.id', '=', 'contents.content_type_id')
->join('favorites', 'favorites.contents_id', '=', 'contents.id') // or whatever the relation is
->with(['platforms', 'classifications'])
->withCount(['favorite'])
->withCount('likes')
->where('favorites.user_id', '=', $this->request->user()->getIdentifier())
->inRandomOrder();
return $query;

How can I used "if" condition in "whereIn" in laravel

Below is my query which one i used and working fine for me.
if($t_requested['category_id'])
{
$t_query_condition['p.category_id'] = $t_requested['category_id'];
}
if($t_requested['brand_id'])
{
$t_query_condition['p.brand_id'] = $t_requested['brand_id'];
}
$browseData = DB::table('products as p')
->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
'p.short_description','p.product_price','p.special_price','p.stock_quantity')
->orderBy('p.created_by', "desc")
->offset(0)
->limit(10)
->where($t_query_condition)
->get();
but Now i have getting multiple id in "category_id" and "brand_id", i want to used whereIn but it used with of condition. if i get category_id or brand_id null then it's skip.
thanks in advance.
Try this query hope you will get result
$browseData = DB::table('products as p')
->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
'p.short_description','p.product_price','p.special_price','p.stock_quantity')
->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
->orderBy('p.created_by', "desc");
if($t_requested['category_id'])
{
$browseData->whereIn('p.category_id',$t_requested['category_id']);
}
if($t_requested['brand_id'])
{
$browseData->whereIn('p.brand_id',$t_requested['brand_id']);
}
$result=browseData->offset(0)->limit(10)->get();
I think it is very simple, you have to pass array of values instead of one value
I have tried to write options for achieve this, you have to follow which is suitable for you
if($t_requested['category_id'])
{
$t_query_condition['p.category_id'] = $t_requested['category_id']; // it should be array OR
$t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
$t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
$t_query_condition['p.category_id'] = [$t_requested['category_id']]; // if you want to convert one value into array
}

Laravel paginator display more pages

what i am trying to do is to get distinct values (date) of my Model and for each date the display the corresponding data. When i make pagination of the distinct dates, it works fine, but in the pagination pages i see all the results instead of the distinct. Here is my function:
public function showdaily($id) {
$capacities = array();
// DB::enableQueryLog();
$capacity_daily = CapacityDaily::select('for_date')->where('capacity_id', '=', $id)->orderBy('for_date', 'asc')->distinct()->paginate(2);
// dd(DB::getQueryLog());
foreach($capacity_daily as $cap) {
$get_capacity = CapacityDaily::where('capacity_id', '=', $id)->where('for_date', '=', $cap->for_date)->orderBy('for_date', 'asc')->distinct()->get();
$capacities[] = array('for_date' => $cap->for_date, 'values' => $get_capacity, 'capacity' => Capacity::find($id)->first());
}
return view('admin.capacity.daily', compact('capacities', 'capacity_daily', 'id'));
}
I have totally 4 distinct dates and 96 rows in that table. As i want to display only 2 dates per page it should show me only one additional page available, but instead of that i have from 1-47.
What i make wrong ?
The toSql() method will show the query it is running, but I suspect you need to group on for_date rather than use distinct
$capacity_daily = CapacityDaily::select('for_date')->where('capacity_id', '=', $id)->orderBy('for_date', 'asc')->groupBy('for_date')->paginate(2);

Laravel Join Returning odd values

Just come across a bug on my Join query.
I am echoing out data in a foreach, and showing the username. On other pages it works fine and each username matches the username from the ID in the row. However, in the example below the username return is ALWAYS the name of the logged in user.
Hope the below makes some more sense. Thanks.
The query is:
$query = DB::table('blogs')
->join('followers', 'blogs.id', '=', 'followers.blogid')
->where('followers.userid', Auth::user()->id)
->where('frontpage', '1')
->latest('lastupdated');
This is called via:
Route::get('following', array('before' => 'auth', function()
{
$slug = Route::getCurrentRoute()->uri();
$builds = Blog::findBuilds($slug);
return View::make('pages/home', compact('builds'), array('pageTitle' => 'Builds You Are Following'));
}));
And then on the pages/home I am showing the data like so:
foreach ($builds as $build)
{
$usernameOfOwner = User::usernameFromID($build->userid);
}
And then... the function for getting the username from ID is:
public static function usernameFromID($id) {
$user = DB::table('users')->where('id', $id)->first();
return $user->username;
}
Everywhere else on my website when I run a query similiar to the top one but not a join so e.g.:
$query = static::where('frontpage', '1')->latest('lastupdated');
It works fine, so my only guess is that its down to the Join as thats the only different part of the code.
The problem is that you have multiple columns named userid. followers.userid and blogs.userid. Now in this case, unfortunately followers.userid gets returned when you use $build->userid
You can change that by only selecting the columns you want in your result.
$userid = Auth::user()->id;
$query = DB::table('blogs')
->join('followers', function($q) use ($userid){
$q->on('blogs.id', '=', 'followers.blogid');
$q->where('followers.userid', '=', $userid);
})
->select('blogs.userid', 'other-column')
->where('frontpage', '1')
->latest('lastupdated');
By the way: * works too, so you can do select('blogs.*') if you want

Categories