I'm trying to get the name of the category to show in a table but I get the error: "Trying to get property 'category' of non-object (View: C:\xampp\htdocs\retro\resources\views\admin\games\index.blade.php)! instead
Here is the table for the code:
@foreach($games as $game)
<tr>
<td>{{ $game->title }}</td>
<td>{{ $game->image }}</td>
<td>£{{ $game->price }}</td>
<td>{{ $game->category_id->category }}</td>
<td>{{ $game->sold }}</td>
<td>{{ $game->promote }}</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit">Edit</button>
</td>
</tr>
@endforeach
The Categories
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
public function games()
{
return $this->hasMany('App\Games');
}
}
The Games
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Games extends Model
{
public function category()
{
return $this->hasOne('App\Categories');
}
}
And here's the migration I'm using
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('image');
$table->integer('price');
$table->integer('category_id')->index();
$table->integer('sold');
$table->integer('promote');
$table->timestamps();
});
}
I'm quite sure it's a relationship error but I can't see what that is.
$game->category_id
contains, maybe an integer (just as you defined it)? – Nico Haase