Laravel : How to get object in column with query builder - php

I want to display what kind of data I have described below, but I don't know the keywords.
For now, this is my data:
And this is the result I want:
This is, my controller:
$data = DB::table('tr_doctor_schedules as sch')
->select('sch.id as schedule_id','doctor_name','hospital_name','estimated_practice_time','day','from_time','until_time')
->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
->where('sch.hospital_id', $hosId)
->where('sch.doctor_id', $docId)
->first();
if ($data) {
return response()->json([
'success' => true,
'message' =>'success',
'data' => $data
], 200);
} else {
return response()->json([
'success' => false,
'message' => 'Data not found.',
], 400);
}
Thanks

Try this
$data = DB::table('tr_doctor_schedules as sch')
->selectRaw('sch.id as schedule_id,doctor_name,hospital_name,estimated_practice_time,GROUP_CONCAT(day) as day,from_time,until_time')
->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
->where('sch.hospital_id', $hosId)
->where('sch.doctor_id', $docId)
->groupBy('sch.id')
->first();

Related

Property [id] does not exist on this collection instance?

I want to show from UserController how many products the User used and user information. I have created two Resources for it. SO I search him using $id Here is My UserController code
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
And here is my UserProductResource
<?php
namespace App\Http\Resources;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
class UserProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'profile_img' => $this->profile_img,
'products' => ProductResource::make($this->products),
];
}
}
And The error is
My Route is:
Route::get('/show-product/{id}', [UserController::class, 'showProduct']);
Try this solution:
You have a error in this query
$products = Product::where('user_id', $user_id)->get();
because $user_id is an object of the User, not a single value.
Your Code:
public function show($id)
{
//
$user_id = User::find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user_id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
New Code:
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
find($id) returns an object so you cant pass object in where(). Replace your below line
$products = Product::where('user_id', $user_id)->get();
with this line
$products = Product::where('user_id', $user_id->id)->get();
it will work.
new UserProductResource($products)
Here Object of Products is passed in resource file and if we check fields in UserProductResource they look like fields existing in User model.
Will $products have any field or relation like products ?
$products is a collection so UserProductResource::collection() should be used.
Ideally you should make relationship between User and Product and do this
$user = User::with('products')->find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
return response()->json([
'data' => new UserProductResource($user),
'status' => 200
], 200);
and as there can be multiple products in UserProductResource you can do this
'products' => ProductResource::collection($this->products),

Laravel - Hide a specific column [duplicate]

This question already has answers here:
Laravel - Method Illuminate\\Support\\Collection::makeHidden does not exist
(4 answers)
Closed 1 year ago.
I want to hide the columns password & OTP ,that is included in $users result. Actually these 2 columns are part of the users table. My ultimate need is that i need to join 3 tables : users,location,user_technical_details and want to hide the password & OTP columns in the users table. Can use any methods. Through any methods, i want to attain this result I've tried many methods. Nothing works. How to solve this? Any suggestions..
Things i tried:
1)
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
$d=$users->makeHidden(['password','OTP']);
return response()->json([
'message' => 'profile viewed successfully',
'data' => $d,
'statusCode' => 200,
'status' => 'success'],200);
This generates the error - Method Illuminate\\Support\\Collection::makeHidden does not exist
2)
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
$exclude_columns=['password','OTP'];
$get_columns = array_diff($users, $exclude_columns)->get();
return response()->json([
'message' => 'profile viewed successfully',
'data' => $get_columns,
'statusCode' => 200,
'status' => 'success'],200);
3)
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
$d=collect($users->toArray())->except(['password','OTP']);
return response()->json([
'message' => 'profile viewed successfully',
'data' => $d,
'statusCode' => 200,
'status' => 'success'],200);
4)
protected $hidden = ['password','OTP'];
5)
$users = DB::table('users')->exclude(['password','OTP','ph_OTP','email_OTP','user_access_token','remember_token'])
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
return response()->json([
'message' => 'profile viewed successfully',
'data' => $users,
'statusCode' => 200,
'status' => 'success'],200);
This generates the Error -Call to undefined method Illuminate\\Database\\Query\\Builder::exclude()
when you want to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden property to your model. In attributes that are listed in the $hidden property's array will not be included in the serialized representation of your model:
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = ['password','OTP'];
}
now in your code you have to use User model instead of DB facade:
$users = User::query()
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
now, $users will not have the hidden attributes

How to select field name using with relation in laravel

I am trying to get field name using with relation:
My Code:
public function getAllUsers()
{
$users = User::with('userBasicInfo','roles:name')->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}
when i simply use $users = User::with('userBasicInfo','roles)->get();
it returns my record accurately and when I used $users = User::with('userBasicInfo','roles:name')->get();
It returns my null array of roles I also want to display name using roles: name but it returns nothing.
You should try this:
public function getAllUsers()
{
$users = DB::table('users')
->select('users.name','roles.name')
->join('userBasicInfo', 'users.userbasicinfo_id', '=', 'userBasicInfo.id')
->join('roles', 'users.roles_id', '=', 'roles.id')
->get();
OR
$users = User::with(['userBasicInfo','roles:name'])->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}

Understanding method in laravel/php

I am working on laravel/php in which I am checking how the method that is being used in the controller to return the view.
public function client($uuid) {
$client = clients::with([
'client_details' => function($q){
$q->with([
'client_ratings' => function($q){
$q->with(['rating_review',
'rating_user' => function($q){
$q->select('user_id','first_name','last_name');
},
'rating_user_media' => function($q) {
$q->select('client_id','owner_id','url')->where('media_type','image')->where('context','user');
}]);
$q->orderBy('created_at', 'desc');
$q->take(2);
}]);
},'owner_details','media','cancellation_policy'])->where('uuid',$uuid)->first();
$groups = groups::getgroups(NULL);
$data = [
'groups' => $groups,
'client' => $client
];
//echo '<pre>';var_dump(json_decode(json_encode($data)));exit;
return View::make('client',['data'=>$data]);
}
Problem Statement:
The above php code is creating the JSON but I am not sure how is this JSON getting created.

Compile loop after data return

I went to build an API using Lumen. i tryed to get data with a condition,
it's successfully return my data. My code is:
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
But i went when it's return my data, some field will update automicatly.
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
// return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
foreach($speeches as $speechreq){
$speechreq->update([
'user_id' => Auth::user()->id,
'is_requested' => 1,
]);
return response()->json(['status'=> 'Success', 'data' => $speechreq], 200);
it returns only one data with the update. but I need 25 data. If I write my code like
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
foreach($speeches as $speechreq){
$speechreq->update([
'user_id' => Auth::user()->id,
'is_requested' => 1,
]);
// return response()->json(['status'=> 'Success', 'data' => $speechreq], 200);
}
it returns me 25 data but foreach loop doesn't work. So can anyone help me, please...?
Return this line after foreach loop.
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);

Categories