Reputation: 402
Hi I'm building a ticket system i made tables with heads as:
<table class="table">
<thead>
<tr>
<th>Category</th>
<th>Title</th>
<th>Status</th>
<th>Last Updated</th>
</tr>
</thead>
I'm having trouble calling category name in views:
@foreach ($tickets as $ticket)
@foreach ($categories as $category)
@if ($category->id === $ticket->category_id)
{{ $category->name }}
@endif
@endforeach
My @if statements seems to be wrong i thinks as i can pull all the category names but with @if code seems to be breaking and its showing me nothing.
My routes:
Route::get('my_tickets', 'TicketsController@userTickets');
My Controller Function:
public function userTickets()
{
$tickets = Ticket::where('user_id', Auth::user()->id)->paginate(10);
$categories = Category::all();
return view('tickets.user_tickets', compact('tickets', 'categories'));
}
Update: My Category Model:
protected $fillable = ['name'];
public function tickets()
{
return $this->hasMany(Ticket::class);
}
&Ticket Model:
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'title', 'priority', 'message', 'status'
];
public function category()
{
return $this->belongsTo(Category::class);
}
I'm trying to follow this tutorial but i think I'm doing something wrong idk what. https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-1 https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-2
Upvotes: 0
Views: 182
Reputation: 2501
I think that you are trying to do something like this:
@foreach ($tickets as $ticket)
{{ $ticket->category->name }}
@endforeach
If you made a relation between your classes with belongsTo and hasMany then you can access using $ticket->category->name. If it does not work perhaps you have to get tickets with:
$tickets = Ticket::with('category')->where('user_id', Auth::user()->id)->paginate(10);
Upvotes: 1
Reputation: 1452
You haven't really followed it through. See how it's done in the article
@foreach ($tickets as $ticket)
@foreach ($categories as $category)
@if ($category->id === $ticket->category_id)
{{ $category->name }}
@endif
@endforeach
$ticket->$category
is not a valid syntax.
Upvotes: 1