Hey all, just getting my hands dirty with laravel and something has me stumped which should seem pretty simple but even after watching 5 Fundamentals, 5.4 From Scratch and Build a Forum with TDD and Laravel I cannot for the life of me pull off the simple task of sending the results of my query to my controller/view.
I have a users, projects and a pivot table, project_user. The table projects contains projects that would have a many-to-many relationship to users and also users have a many-to-many to projects.
In my User model I have...
public function projects()
{
return $this->belongsToMany(Project::class)->wherePivot('user_id', 1);
}
}
// I hard coded the value of user user_id,1 but ultimately this value should be the current logged in user.
Project model
public function users()
{
return $this->belongsToMany(User::class)->wherePivot('user_id', 1);
}
In my ProjectsController
public function index()
{
$projects = Project::all()->where('status', 1);
return view('projects.show', compact('project'));
}
So this will successfully return all of the projects with a status of 1 but I only want to return the ones that have a relationship to the current logged in user.
No matter what I do I cannot access the projects() method from the User model. Should I be able to? How do I return the results of my query to the correct controller to pass to my view?
In tinker I get the results that I want, at least it would appear so...
$ php artisan tinker
Psy Shell v0.8.13 (PHP 7.1.9 — cli) by Justin Hilemanan
>>> $user = App\User::find(1);
=> App\User {#778
id: "1",
first_name: "Kevin",
last_name: "XXXX",
company_name: "XXXX",
app_role_id: "1",
project_id: "1",
discipline_id: "1",
project_role_id: "1",
contact_id: "1",
active_phases: "1",
status: "1",
verified: "0",
email: "XXXX",
cell_phone: "XXXXX",
user_profile_pic: "nopic.png",
created_at: "2017-10-28 16:48:24.000",
updated_at: "2017-10-28 16:48:24.000",
}
>>> $user->projects
=> Illuminate\Database\Eloquent\Collection {#774
all: [
App\Project {#119
id: "1",
ProjectName: "Viper",
contact_id: "2",
created_by: "1",
status: "1",
created_at: null,
updated_at: null,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#777
user_id: "1",
project_id: "1",
},
contact: App\User {#787
id: "2",
first_name: "Robert",
last_name: "XXXX",
company_name: "XXXX.",
app_role_id: "1",
project_id: "1",
discipline_id: "1",
project_role_id: "1",
contact_id: "1",
active_phases: "1",
status: "1",
verified: "0",
email: "email address",
cell_phone: "2223334455",
user_profile_pic: "nopic.png",
created_at: "2017-10-30 23:45:42.000",
updated_at: "2017-10-30 23:45:42.000",
},
},
],
}
Route
Route::get('projects', 'ProjectsController@index');
Appreciate the help!
Thanks,
Kevin