lundi 21 mai 2018

Error trying to output the Eloquent relationship in Laravel

I'm getting the error "Trying to get property 'company_name' of non-object". I studied about the Eloquent relationship and try to implement in my code. But it gives me that error in the view (products.show)

Which part are wrong?

Is it okay to have many different relationship to other model as well?

In 'Vendor Model':

public function getRouteKeyName()
{
    return 'roc_no';
}

public function user()
{
    return $this->belongsTo('App\User');
}

public function products()
{
    return $this->hasMany('App\Product');
}

In 'Product Model':

public function getRouteKeyName()
{
    return 'slug';
}

public function user()
{
    return $this->belongsTo('App\User');
}

public function vendor()
{
    return $this->belongsTo('App\Vendor');
}

In 'User Model':

    public function vendor()
    {
        return $this->hasOne('App\Vendor');
    }

    public function products()
    {
        return $this->hasMany('App\Product');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'role_users');
    }

In the 'products.show':

...    
{!! $product->description !!}
<!-- The error is at $product->vendor->company_name -->
Company Name: <a href="/vendors/"></a>

In 'ProductController':

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:100',
            'description' => 'required',
            'image' => 'nullable',
        ]);

        $product = new Product;
        $product->name = $request->name;
        $product->slug = $request->slug;
        $product->description = $request->description;
        $product->vendor_roc_no = auth()->user()->vendor->roc_no;
        $product->save();

        return redirect('/account/products')->with('success', 'Product added successfully.');
    }

    public function show(Product $product)
    {    
        return view('products.show')->with('product', $product);
    }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2kgRi0J
via IFTTT

Aucun commentaire:

Enregistrer un commentaire