redshot redshot - 1 month ago 7
HTML Question

How to access the field of a foreign table in Laravel 5?

I am retrieving values of a foreign table in my CRUD. I have a tickets table with a ticket status. The tickets table has foreign_key of ticket_statuses table.

TicketsController.php

public function create()
{
$users = User::all();
$ticketstatus = TicketStatus::all();
$tickets = Ticket::paginate(25);
return View::make('user.tickets.create', compact('users','ticketstatus','tickets'));
}


create.blade.php

<div class="form-group">

{!! Form::label('status', 'Status', ['class' => 'col-md-4 control-label']) !!}

<div class="col-md-6">

<select class="form-control form-field-ticket form-field-users">
@foreach($tickets as $item)
<option value="">{{$item->ticketstatus->status}}</option>
@endforeach
</select>

</div>

</div>


Ticket.php

public function ticketstatus()
{
return $this->belongsTo('App\TicketStatus', 'ticket_status_id', 'id');
}


TicketStatus.php

// Ticket Status __has_many__ Ticket
public function tickets()
{
return $this->hasMany('Ticket');
}


.

@foreach($tickets as $item)
<option value="">{{$item->ticketstatus->status}}</option>
@endforeach


Thew code above gives the field of tickets table.

I want to access the $item->ticketstatus->status of ticket_statuses field of ticket_statuses table.

What do i need to do to be able to access that field? Any help is appreciated. Thanks

Answer

I think one ticket has only one status so, it is a one to one relationship.

In Ticket.php

public function ticket_status(){
    return $this->hasOne('App\TicketStatus','id','ticket_status_id');
}

Then,

    @foreach($tickets as $item)
        <option value="">{{$item->ticket_status->status}}</option>
    @endforeach 
Comments