I am a new to laravel can anybody help?
Tables structure
1) rooms
id |roomno |roomtype_id |luxurytype |status
2) roomtypes
id| code| description
Models code
1) roomtype model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomtype extends Model
{
public function rooms(){
return $this->hasMany('App\room');
}
}
2)room model
namespace App;
use Illuminate\Database\Eloquent\Model;
class room extends Model
{
public function roomtypes(){
return $this->belongsTo('App\roomtype');
}
}
Controller
public function index()
{
$roomtype = roomtype::all();
$rooms = room::all();
return view('home', array('roomtype'=>$roomtype , 'rooms'=>$rooms));
}
View
@foreach ($rooms as $rooms)
<tr>
<td>{{ $rooms->roomno }}</td>
<td>{{ $rooms->luxurytype }}</td>
<td>{{ $rooms->roomtypes->description }}</td>
<td>{{ $rooms->status }}</td>
<td></td>
</tr>
@endforeach
Error
If I use this line {{ $rooms->roomtypes->description }}
then am getting:
Trying to get property of non-object
(View: C:\xampp\htdocs\hms\resources\views\home.blade.php)
How can I show the room with its roomtype description?
Change your controller file like this
public function index()
{
$rooms = room::with('roomtypes')->get();
return view('home', array('rooms'=>$rooms));
}
Now access room type in blade view in following way-:
@foreach ($rooms as $rooms)
<tr>
<td>{{ $rooms->roomno }}</td>
<td>{{ $rooms->luxurytype }}</td>
<td>{{ $rooms->roomtypes[0]->description }}</td>
<td>{{ $rooms->status }}</td>
<td></td>
</tr>
@endforeach