redshot redshot - 2 months ago 14
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:

protected $appends = ['full_name', 'avatar'];

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

* Display a listing of the resource.
public function index()
$tickets = Ticket::paginate(25);

$users = User::all();

//return view('', compact('tickets'));
return View::make('', compact('tickets','users'));


<table class="table table-striped table-bordered">
<th>Assigned To</th>

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



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.


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.