Post Model:
class Post extends Model
{
protected $fillable = [
'name',
'image',
'genders_id',
'categories_id',
'sizes_id',
'price'
];
public function category()
{
return $this->hasOne(Category::class, 'id');
}
public function gender()
{
return $this->hasOne(Gender::class, 'id');
}
public function size()
{
return $this->hasOne(Size::class, 'id');
}
}
index.blade.php:
@foreach ($posts as $post)
<td><img src="{{ url('storage/'. $post->image) }}" width="100" height="50"></td>
<td>{{ $post->name }}</td>
<td>{{ $post->size->name }}</td>
<td>{{ $post->category->name }}</td>
<td>{{ $post->gender->name }}</td>
<td>{{ $post->price }} $</td>
<td></td>
</tbody>
@endforeach
Posts table:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('genders_id');
$table->string('sizes_id');
$table->string('categories_id');
$table->integer('price');
$table->string('image');
$table->timestamps();
});
}
PostsController:
public function store(PostValidation $request)
{
$image = $request->file('image')->store('image');
Post::create([
'name' => $request->name,
'image' => $image,
'genders_id' => $request->gender,
'categories_id' => $request->categories,
'sizes_id' => $request->size,
'price' => $request->price
]);
return redirect(route('post.index'));
}
The issue is {{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }} works after my first post, whenever I add a second post it gives me the following error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php) {{ $post->size->name }}
sizes_id,genders_idandcategories_idarenullfor the second post so you cannot call the relationship because they will returnnull, so you are essentially doing{{ $post->null->name }}atm. - Remul