Home > OS >  LARAVEL: How to fetch id dynamically in a query builder?
LARAVEL: How to fetch id dynamically in a query builder?

Time:05-14

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:

 $datauser = DB::table('users')
    ->join('activitates','users.id','=','activitates.user_id')
    ->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
    ->join('clients','users.id','=','clients.user_id')
    ->where('users.id','=','1')
    ->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
    ->get();
    return response()->json($datauser);

But I would want something like this(which I just can't seem to figure out)

public function showuser($id)
{
$userid = User::findOrFail($id);
    $datauser = DB::table('users')
    ->join('activitates','users.id','=','activitates.user_id')
    ->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
    ->join('clients','users.id','=','clients.user_id')
    ->where('users.id','=',$userid)
    ->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
    ->get();
   
    return response()->json($datauser);
}

Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data

CodePudding user response:

The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:

$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();

return response()->json($datauser);

CodePudding user response:

public function showuser($id)
{
    $getUserByID = User::findOrFail($id); //not used
    $userData = DB::table('users')
    ->join('activitates','users.id','=','activitates.user_id')
    ->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
    ->join('clients','users.id','=','clients.user_id')
    ->where('users.id','=',$id)
    ->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
    ->get();
   
    return response()->json($userData);
}

But the best way is to have relations set on models

public function showuser($id)
{
   $userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
   return response()->json($userData);
}
  • Related