I have 2 Models, User and Project...
A User has a Project but it can invite other Users to work in this Project...
How I do query all my projects, the ones I own and the ones I have been assigned.
Setup a Many to Many relationship between Users and Projects. This will result in three tables users, projects, and project_user. Your User model will look like this:
<?php
namespace App;
use App\Project;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
...
public function projects()
{
return $this->belongsToMany(Project::class);
}
...
}
Then you'll be able to do exactly what you wanted:
$projects = User::find(1)->projects;
// or for the current authenticated user
$projects = auth()->user()->projects;
This example in the documentation is pretty much exactly what you want:
Thank you for your answer.... But If a User is the owner of a project the Project model will contains the user_id attribute no? And I will need to make another relationship of the Users model
public function projectsAsOwner()
{
return $this->hasMany(Project:class);
}
Or should I use the belongs to Many and use a pivot field to set the owner?
@SOCIEBOY - I would just add an owner_id field to your projects table and setup your relationships this way:
// project model
class Project extends Model
{
protected $guarded = [];
public function owner()
{
return $this->belongsTo(User::class, 'owner_id')->withDefault([
'owner_id' => auth()->id(),
]);
}
public function users()
{
return $this->belongsToMany(User::class);
}
}
// user model
class User extends Authenticatable
{
...
public function projects()
{
return $this->belongsToMany(Project::class);
}
public function ownedProjects()
{
return $this->hasMany(Project::class, 'owner_id');
}
}