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);
}
Related
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),
So, I have a pivot table called user_filmscores, where the users can ''follow (watching, dropped, hold-on...)'' a film and add a rating on it.
In the userController I have this function:
public function userFilm(Request $request){
$data = $request->all();
$validator=Validator::make($data,[
'user_id' => 'required',
'film_id' => 'required',
'state' => 'required',
'score' => 'nullable'
]);
if($validator->fails()){
return response()->json([
'ok' => false,
'error' => $validator->messages(),
]);
}
$film = Film::find($data['film_id']);
$user = User::find($data['user_id']);
$filmId=$data['film_id'];
$userId=$data['user_id'];
//Check if the relationship exists (I tried many methods but always the same result with false)
/*$hasFilm = User::where('id', $data['user_id'])->whereHas('film', function ($q) use ($filmId) {
$q->where('id', $filmId);
})->exists();*/
$hasFilm = $user->film()->where('film_id', '=', $filmId)->exists();
/*$user->film()->sync($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);*/
if(User::where('id', $userId)->where('id')){
$user->film()->attach($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);
}else{
$user->film()->detach($film->getKey());
}
}
In the final part of the code, I want to check if the relationship between the user and the film exists, to make an action or another. But when I try to check if the relationship exists, it always returns me a false.
I thought to do it like, if there is a relationship, first delete the old relationship, and then create a new one.
I don't know if there is a better way to do it.
User model has this function:
public function film(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'user_id', 'film_id', 'state', 'score');
}
Film model has this function:
public function user(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'film_id', 'user_id', 'state', 'score');
}
Users table:
Films table:
User_filmscores table:
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();
I can't access $prospectus in the function show() but works well in the function store() in laravel version 5.6.27
public function store(Request $request) {
$course = Course::create([
'name' => $request['name'],
'title' => $request['title'],
'division_id' => $request['division_id'],
]);
$prospectus = Prospectus::create([
'years' => $request['years'],
'name' => $course->name,
'user_id' => null,
'course_id' => $course->id,
]);
return view('courses.show', compact('course', 'prospectus'));
}
public function show(Course $course) {
$prospectus = Prospectus::where('course_id', $course->id)->get();
//return $prospectus;
return view('courses.show', compact('course', 'prospectus'));
}
the data is passed when i use return $prospectus; but not in return view('courses.show', compact('course', 'prospectus'));
here are my routes
Route::resource('courses', 'CourseController');
Route::post('courses', 'CourseController#store')->name('courses.store');
Route::get('courses/{course}', 'CourseController#show')->name('courses.show');
I supose you want a single Prospectus object, get() will give you a collection of objects.
Use the first() function to get only the first match from the database as a single object.
$prospectus = Prospectus::where('course_id', $course->id)->first();
Confirm that $prospectus query don't return NULL
Try this:
$prospectus = Prospectus::where('course_id', $course->id)->first();
I would like to create an orderBy ('created_at', 'desc') and paginate, for my articles posted in my account, here is my code.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'events' => $user->events,
'articles' => $user->articles,
]);
}
Assuming the relationship is correct on the User model:
'articles' => $user->articles()->orderByDesc('created_at')->paginate()