Home > Enterprise >  how to use Join with Where condition in laravel controller?
how to use Join with Where condition in laravel controller?

Time:08-14

i have this index function that will show data from two different tables:

public function index()
{
    $complaints = DB::table('complaint')
    ->select(['complaint.id','complaint.createdDate','complaint.user_id','complaint.createdDate','complaint.complaint_title','tbl_users.phone','tbl_users.email'])
    ->join('tbl_users', 'complaint.user_id', '=', 'tbl_users.id')
    ->get();

    return view('admin.complaints',compact('complaints'));
}

and in the next function i want to show a single row using the same thing above by 'id'

i tired this:

public function show($id)
{
    $complaints = DB::table('complaint')
    ->select(['complaint.id','complaint.createdDate','complaint.user_id','complaint.createdDate','complaint.complaint_title','tbl_users.phone','tbl_users.email'])
    ->join('tbl_users', 'complaint.user_id', '=', 'tbl_users.id')
    ->where('id', $id)->first()
    ->get();


    return $complaints;

}

but i'm getting this error

Call to undefined method stdClass::get()

CodePudding user response:

For creating where statements, you can use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records , so you should delete first() , so the code should be like that .

public function show($id)
{
    $complaints = DB::table('complaint')
    ->select(['complaint.id','complaint.createdDate','complaint.user_id','complaint.createdDate','complaint.complaint_title','tbl_users.phone','tbl_users.email'])
    ->join('tbl_users', 'complaint.user_id', '=', 'tbl_users.id')
    ->where('id', $id)
    ->get();


    return $complaints;

}
  • Related