Farshad
Farshad

Reputation: 2000

retrieve data from pivot table many to many relation ship laravel 5

i made a many to many relationship in laravel and it works fine but when i want to retrive and show my data some thing strange happens now i want to show the clients which are assigned to the logged in user so here is my code client model :

public function sellmanlist(){
    return $this->belongsToMany('App\User' , 'client_user','client_id');
}

Controller and the method for retreive

public function myclient(Client $client){
    $user_id =Auth::user()->id;
    $client = Client::with('sellmanlist')->firstOrFail();
    return view('admin.client.myclient',compact('user_id','client'));
}

and here is the view that i am testing already

@foreach($client->sellmanlist as $sellman )
            @php(
            $sell_id = $sellman->pivot->user_id
            )
            @if($user_id === $sell_id)
                {{$client->id}}
                {{$client->title}}
            <br>
                @endif
            @endforeach

but this only shows the client id of 1 2 times and here is my pivot table

 public function up()
{
    Schema::create('client_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('client_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

Upvotes: 1

Views: 42

Answers (1)

rkj
rkj

Reputation: 8287

Just add a reverse belongsToMany relationship in User model for Client

User Model

public function clients(){
    return $this->belongsToMany('App\Client','client_user');
}

Now fetch clients for logged in user in controller

public function myclient(Client $client){
    $user = Auth::user();
    $user->load('clients'); //lazy-eager loading
    return view('admin.client.myclient',compact('user','client'));
}

Display it in view

@foreach($user->clients as $client )
   {{$client->id}}
   {{$client->title}}
   <br>
@endforeach

Upvotes: 1

Related Questions