anis
anis

Reputation: 885

i want to return the projects of specific user?

I want to return the projects of the authenticated user, but am not getting any. I know the records exist in the database.

This is my model Project:

public function users(){
    return $this->hasMany(User::class);
}

this is my model User:

public function projects(){
    return $this->hasMany(Projet::class,'user_id');
}

and this is the controller function :

public function projetuser(){
   $user = User::find(auth()->user()->id);
   return $user->projects;
}

and this my user_projet migration:

public function up()
{
    Schema::create('user_projet', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->unsignedBigInteger('projet_id');
        $table->foreign('projet_id')->references('id')->on('projets')->onDelete('cascade');

        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->string('membre')->nullbale();
        $table->timestamps();
    });
}

Upvotes: 0

Views: 51

Answers (1)

miken32
miken32

Reputation: 42716

You are defining a many-to-many relationship incorrectly. Use belongsToMany() instead of hasMany(). Because your pivot table name is not standard (it should be alphabetic order projet_user) you need to include it in the relationship definition as well.

<?php

use Illuminate\Database\Eloquent\Model;

class Projet extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'user_projet');
    }
}

class User extends Model
{
    public function projets(){
        return $this->belongsToMany(Projet::class, 'user_projet');
    }
}

Now in your controller you can do this:

public function projetuser(){
    return auth()->user->projets;
}

Your question seems to vary between "projet" and "project." I assumed "projet" was the correct spelling, but try to keep this consistent.

Please note also the typo in your migration: nullbale.

Upvotes: 1

Related Questions