Ainee Chong Ainee Chong - 1 month ago 7
PHP Question

How to do where on with model in laravel?

So I have this condition where I need to filter the project list according to the login user if the user is inside the members() model.

public function index(Request $request = null, $search = null)
{
$user = $this->user;
$data = project_registry::with('members', 'members.profile')->where('isdelete', 0);

if(!$user->project_view) {
// here i need to do the filter for the login user to view project where they are the member of the project
}

if(!is_null($request['search'])) {
$search = $request['search'];
$data->where(function($q) use ($search) {
$q->where('Project_Code', 'LIKE', "%$search%")->orWhere('Project_Short_name', 'LIKE', "%$search%");
});
}

$data = $data->orderBy('Project_ID')->paginate(20);

return view('project.index', compact('data', 'search'));
}

Answer

use wherehas

project_registry::whereHas('members', function($q) use ($user) {
    $q->where('user_id', $user->id);
})->...