redshot redshot - 18 days ago 7
HTML Question

How to get the column values according to id inside blade and controller in Laravel?

I am retrieving all Tickets assigned to a user. A single ticket has a foreign key to users table. These are the code below:

App\Models\User.php
protected $appends = ['full_name', 'avatar'];

public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}


App\Http\Controllers\TicketsController.php
/**
* Display a listing of the resource.
*/
public function index()
{
$tickets = Ticket::paginate(25);

$users = User::all();

//return view('user.tickets.index', compact('tickets'));
return View::make('user.tickets.index', compact('tickets','users'));
}

Resources/Views/User/Tickets/index.blade.php

<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Status</th>
<th>Assigned To</th>
</tr>
</thead>
<tbody>

@foreach($tickets as $item)
<tr>
<td>{{ $item->status }}</td>
<td>{{ $item->user_id }}</td>
</tr>
@endforeach


</tbody>

</table>


I want to convert the field {{ $item->user_id }} into {{ $item->first_name where id = $item->user_id }} The field should be converted into the First Name according to the $item->user_id

user_id is a foreign key to tickets and the equivalent of it is the is of Users table.

Please help.

Answer

Firstly it's not good practice to write db query in views. You can accomplish that by defining a relation in your Ticket model class.

public function user()
{
    return $this->belongsTo(User::class);
}

Now you can access user name by $item->user->first_name.