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.
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
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With