ErrorException
Trying to get property 'category_name' of non-object (View: D:\xampp\htdocs\e-catalog\resources\views\backend\pages\gmproducts.blade.php)
This is my blade code below.
<tbody>
@foreach($gmproducts as $no => $gm)
<tr>
<td>{{$no 1}}</td>
<td>{{$gm->type}}</td>
<td>{{$gm->gmcategories->category_name}}</td>
<td>{{$gm->gram}}</td>
<td>{{$gm->carat}}</td>
<td>@currency($gm->price)</td>
<td><a href="{{url('p_goldmart/'.$gm->file)}}">Preview</a></td>
<td>
<a href="/gmproducts/update/{{$gm->id}}" ><i ></i></a>
<a href="/gmproducts/delete/{{$gm->id}}" ><i ></i></a>
</td>
</tr>
@endforeach
</tbody>
This is my model Gmcategories & Gmproducts.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gmcategories extends Model
{
protected $table = "gmcategories";
protected $fillable = ['category_name'];
public function gmproducts()
{
return $this->hasOne('App\Gmproducts');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Gmproducts extends Model
{
use SoftDeletes;
protected $table = "gmproducts";
protected $fillable = ['type', 'category_id', 'gram', 'carat', 'price', 'file'];
protected $dates = ['deleted_at'];
public function gmcategories()
{
return $this->belongsTo('App\Gmcategories');
}
}
This is my controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Gmproducts;
use App\Gmcategories;
use File;
class GmproductsController extends Controller
{
public function index()
{
$gmproducts = Gmproducts::orderBy('id', 'desc')->get();
$trash = Gmproducts::orderBy('deleted_at', 'desc')->onlyTrashed()->count();
return view('backend.pages.gmproducts', compact('gmproducts', 'trash'));
}
public function create()
{
$gmcategories = Gmcategories::all();
return view('backend.pages.create', compact('gmcategories'));
}
Just info, I just rename my model and controller. Does it have any effect? Thanks.
CodePudding user response:
// Gmcategories
public function gmproducts()
{
return $this->hasOne('App\Gmproducts', 'category_id');
}
// Gmcategories
public function gmcategories()
{
return $this->belongsTo('App\Gmcategories', 'category_id');
}
CodePudding user response:
Your BuildImage model should be
Get the source type of the Building Image.
public function type() {
return $this->hasOne('App\BuildingType',"id","source");
}
And BuildingType Model should be
Get the Building Image that owns the building type.
public function buildingImage()
{
return $this->belongsTo('App\BuildingImage',"source","id");
}