I am working on a task application, and I would like to display the name of the user, who created or updated the task. However, I can only display the id of the user.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Task;
use App\User;
class TaskController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::with(["user"])->get();
$user = User::all();
return view('tasks/index', compact('tasks','user'));
}
index.blade.php:
@foreach($tasks as $task)
<tr>
<td>{{$task->id}}</td>
<td>{{$task->title}}</td>
<td>{{$task->description}}</td>
<td>{{$task->created_at}}</td>
<td>{{$task->user->created_by}}</td>
public function creator()
{
return $this->belongsTo('App\User', 'user_id'); // be sure to set 'user_id` since this relationship is called 'creator' and not 'user'. if you do not do this, it will look for 'creator_id` in the tasks table and you will get 'object not found'
}
You can do the reverse in your User.php (user model)
public function tasks()
{
return $this->hasMany('App\Task');
}
Then in your view
{{ $task->creator->name }} // that is if your users table has a field for 'name'
public function createdBy()
{
return $this->belongsTo(User::class, "created_by");
}
public function updatedBy()
{
return $this->belongsTo(User::class, "updated_by");
}