phplaravelormeloquentrelational-database

Laravel - Eloquent Relationship not working


I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Shop Table

id | name | url 1 | NY | ny | 2 | CA | ca |

Products Table

id | shop_id | slug 1 | 1 | ca 2 | 2 | wa

Shop.php

public function products()
{
    return $this->hasMany(Product::class, 'shop_id');
}

Product Model

 public function shops()
{
    return $this->belongsTo(Shop::class, 'id');
}

Controller.php

public function category($slug)
{

    $shop = Shop::where('url', $slug)->firstorfail();
    $products = Product::with(['shops'])->where(['shop_id' => $shop->id)->get();
    $url = Shop::where('id', $products->shop_id)->pluck('url');
}

Route

Route::get('/{url}/{slug}', 'Controller@category')->name('view')->where('slug', '[\w\d\-]+(.*)');

View

<a href="{{ route('view', [$url, $products->slug]) }}"

It returns Property [shop_id] does not exist on this collection instance.


Solution

  • Try this:  
      public function products(){
            return $this->hasMany('App\Product','shop_id','id');
        }