Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

socieboy's avatar

Query to Relationship

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.

User::find(1)->projects()->get();

0 likes
5 replies
realrandyallen's avatar

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:

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

socieboy's avatar

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?

realrandyallen's avatar
Level 44

@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');
    } 
}

Please or to participate in this conversation.