Search code examples
phplaravel-5laravel-bladetable-relationships

laravel 5: relationship between products and featured products


I'm writing a sample ecommerce website with Laravel 5. I have 2 Tables:

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->text('description');
    $table->float('price');
    $table->integer('category_id');
    $table->timestamps();
});

and

Schema::create('featureds', function (Blueprint $table) {
    $table->integer('product_id')->unique()->unsigned();
});

Schema::table('featureds', function($table) {
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});

Models

class Product extends Model
{
    public function category(){
        return $this->belongsTo('App\Category');
    }    
}

class Featured extends Model
{
    public function product(){
        return $this->hasOne('App\Product', 'product_id');
    }
}

Then, I have a Controller, where I take 4 featured products:

$featured_products = Featured::limit(4)->get();
return view('home', ['featured_products' => $featured_products]);

Now, I'm trying to show these featured products in my view. If i show the product_id from the Featured model, everything is ok:

@foreach($featured_products as $prod)
  {{$prod->product_id}}
@endforeach

But I want to take the name of the product referred by the featured. I tried this way:

@foreach($featured_products as $prod)
  @foreach($prod as $p)
    {{$p->name}}
  @endforeach
@endforeach

Because featured_products (in the controller) seems to be a collection, but it doesn't work!


Solution

  • In your Featured model, you have a relationship in method product() when you want to access the relation from the view, you could call the method name as property, in you case, you have a method named product() so you have to call product property like this:

    @foreach($featured_products as $prod)
        {{ $prod->product->name }}
    @endforeach
    

    It will automatically write the product name based on the relationship you have configured in the model.

    Reference: https://laravel.com/docs/5.2/eloquent-relationships

    Edit:

    Sorry my bad, I guess you are defining a wrong relation, your Product model, should have a featured() method which uses hasOne relation, while Featured model should have a product() method using belongsTo relation. So in you App\Featured model, you have to define the relation like this:

    return $this->belongsTo('App\Product');
    

    And in your App\Product model you should define relation like so:

    return $this->hasOne('App\Featured');
    

    Hope it works