V
V
Vlad Volodko2018-02-01 06:15:24
Laravel
Vlad Volodko, 2018-02-01 06:15:24

How to get data from related Laravel tables?

Hello. There is a table that stores user_id and project_id.
5a7285757f83a887066843.png
To receive project participants, I wrote in the Prohect model

public function member(){
        return $this->hasMany('App\Model\Project\ProjectMember');
    }

И потом в контроллере пишу

$project = Project::find(some_id);
$project->member;

This returns me a list of id's and how do I get information about the user (first name last name...)?
Thank you)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2018-02-01
@Ruless

```public function members()
{
return $this->belongsToMany(User::class, 'project_users');
}```
Then ```->members```

K
Korya, 2018-02-04
@Korya

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function projects()
    {
        return $this->belongsToMany('App\Project', 'project_user');
    }

    public function getFullNameAttribute()
    {
        return "{$this->firstname} {$this->lastname}";
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    public function members()
    {
        return $this->belongsToMany('App\User', 'project_user');
    }
}

$id = 1;
$project = Project::find($id);

@foreach ($project->members as $member) 
    {{ $member->full_name }}
@endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question