im using laravel 5.4 , i have a brand table and a products table and my relations are this :
class Product extends Model
{
protected $table = 'products';
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
And
class Brand extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
My Migrations :
Schema::create('brands', function (Blueprint $table) {
$table->increments('id');
$table->string('name',15)->unique();
$table->string('tag',15)->unique();
$table->mediumInteger('numofads')->unsigned()->default(0);
$table->timestamps();
});
&
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('brand_id')->unsigned();
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
$table->string('name',15)->unique();
$table->string('tag',15)->nullable()->unique();
$table->mediumInteger('numofads')->unsigned()->default(0);
$table->timestamps();
});
in my Controller i will take 3 brand and send them to the view :
public function show()
{
$brands = Brand::take(3)->get();
return view('show',compact('brands'));
}
And in my view i will iterate that to show just products like this:
@foreach($brands as $brand)
{{ $brand->products->name }}
@endforeach
I think everything i ok but i will get error :
ErrorException in Collection.php line 1543:
Property [name] does not exist on this collection instance. (View: /home/k1/Laravel/carsan/resources/views/welcome.blade.php)
$brand->products
is going to be a Collection
. You will have to iterate that. It is not a single model, it potentially contains many models, just like $brands
is a collection of models.
@foreach ($brands as $brand)
...
@foreach ($brand->products as $product)
...
@endforeach
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.