UclidesGil UclidesGil - 16 days ago 5
PHP Question

has many implement in laravel

I find myself starting with laravel and I need a little help from the following:
I have a one-to-many relationship between: a product can have multiple images at the same time, an image belongs to a product. code:

Product:

class Product extends Model
{
public function images(){
return $this->hasMany('App\Image');
}
}


Image:

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


Now to show the View I want to show only the first image of each product, I do this in the controller:

public function index()
{
$products = Product::all();
$products = Product::join('images', 'products.id', '=', 'images.id')->select('products.id','products.denomination_prod','products.description','pooducts.price','images.path')
->get();

return view('products.products', compact('products'));
}


Now you could tell me if this is done correctly. That is I am respecting the standards of good structure?.
I hope you can help me; perhaps a silly question for many but they are my first steps with this excellent framework and would like to learn it the right way.

Answer

There is no need to use join(). You can just use the declared relationship:

$products = Product::with('images')->get();

and then you are going to have an images collection per product. Afterwards you can do whatever you like with each product's images collection. A simple loop might be useful:

@foreach($products as $product)
    <div class="col-lg-4 col-md-6 col-xs-12">
        <img src="{{asset($product->images->first())}}" />
    </div>
@endforeach