relationship and blade in laravel

35,173

Solution 1

A better way is to define inverse hasMany relation in your Model, as documented here

So in your logs model, probably you need to define:

class Log extends Eloquent {
    protected $table = "logs";

    public function user(){
         return $this->belongsTo('User');
    }
    public function task(){
         return $this->belongsTo('Task');
    }
}

Then in your view you can either use :

$log->user()->first()->name

or even better, by using Dynamic Properties:

$log->user->name

Solution 2

$log->users() and $log->tasks() returns a query object. Below, each call returns the result which is the same as calling $log->users()->get() and $log->tasks()->get(). Because the relationships are many to many, you'll need to iterate over $log->users and $log->tasks to retrieve each record.

@foreach($logs as $log)
         <tr>
            <td>{{$log->id}}</td>
            <td>
                @foreach($log->users as $user)
                {{$user->name}},
                @endforeach
            </td>
            <td>
                @foreach($log->tasks as $task)
                {{$task->name}},
                @endforeach
            </td>
        <tr>
@endforeach

If you want a specific user/task attached to a log you'll have to build a query.

@foreach($logs as $log)
         <tr>
            <td>{{$log->id}}</td>
            <td>{{$log->users()->where('id', '=', $userID)->first()->name}} </td>
            <td>{{$log->tasks()->where('id', '=', $taskID)->first()->name}} </td>
        <tr>
@endforeach
Share:
35,173
Daniel Euchar
Author by

Daniel Euchar

Coding.................. Hacking........................... Moding.................................

Updated on July 14, 2022

Comments

  • Daniel Euchar
    Daniel Euchar almost 2 years

    I have 3 table as mentioned below.

    Table 1(user): 
    id    username   password  Name Age
    
    Table 2(tasks):
    id  task_name  description
    
    Table 3(logs) 
    id user_id task_id date hours
    

    Table Relationships:

    user has_many logs
    task has_many logs
    
    logs belongs_to user 
    logs belongs_to  task
    

    what i am trying to achieve is to get the logs with the user Name, task Name, date and hours.

    Controller:

    return View::make('log.index')
                ->with('logs',log::all());
    

    Blade template

    @foreach($logs as $log)
                 <tr>
                    <td>{{$log->id}}</td>
                    <td>{{$log->users()->name}}</td>
                    <td>{{$log->tasks()->name}}</td>
                <tr>
    @endforeach
    

    but unable to fetch users Name and Tasks name from the respective table. any help is appreciated.

  • Naresh
    Naresh over 6 years
    $log->user()->first()->name this will leads to N+1 problem.