John
John

Reputation: 145

how to print project id number using project table in Laravel 5.2

I have collaboration model in My laravel app and consider following form

<div class="container">
      @if($collaboration)
        <div class="row">
        @foreach ($collaboration as $proj)
<div class="col-md-3" style="border:1px solid #ccc;margin-left:5px;">

         <h2><a href="/collaborators/{{ $proj->project_id }}/">{!! $proj->project_id !!}</a></h2>
               <p>Due : {!! date_format(new DateTime($proj->due_date), "D, m Y") !!}</p>
               <p>Status: {!! $proj->project_status !!}</p>
               <p>Tasks: 0</p>
               <p>Comments: 0</p>
               <p>Attachments: 0</p>
               </div>
                @endforeach
         </div>
      @endif

my collaboration model as following.

id project_id collaborator_id
 1     1            1
 2     1            2
 3     2            1  

now I need print project_name instinct project_id

this is my project model

id  project_name
 1       kiu
 2       jhy
 3       juh

how can I do this?

Upvotes: 0

Views: 42

Answers (2)

kunal
kunal

Reputation: 4248

It is very simple you need to use join in your controller function like this way :

 $collaboration = DB::table('collaboration')
                ->join('project ','project.id','=','collaboration.project_id')
                ->select('collaboration.*','project.project_name')
                ->get();
dd($collaboration);

Rest everything will work like same you have added in view file, Hope it helps!

Upvotes: 0

JoshKisb
JoshKisb

Reputation: 752

Use Eloquent Relationships

Collaboration model:

public function project()
{
    return $this->belongsTo('App\Project');
}

Project Model:

public function collaborators()
{
    return $this->hasMany('App\Collaboration', 'collaborator_id');
}

in your controller use eager loading to prefetch collaborations with their related projects

$collaborations = Collaboration::with('project')->get();

Then in your views you can simply get project name with

$proj->project->project_name

Upvotes: 0

Related Questions