Hello I am trying to access the Brand of a Vehicle through a HasMany relationship and receive the Property error, how can I fix it?
Migrations
Vehicles
Schema::create('vehicles', function (Blueprint $table) { $table->id(); $table->integer('year'); $table->string('color'); $table->timestamps(); });
Brands
Schema::create('brands', function (Blueprint $table) { $table->id(); $table->string('name'); $table->foreignId('vehicles_id')->constrained()->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); });
Models
Vehicles
public function Brands() { return $this->BelongsTo(Brand::class,'vehicles_id'); }
Brand
public function Vehicles() { return $this->hasMany(Vehicle::class,'vehicles_id'); }
Method
$V = Vehicle::find($id); dd($V->Brands->name);
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You have relationship the incorrect way.
In your current code One brand (BMW) can be attached only to one vehicle. But in reality it is the other way. Vehicle belongs to one Brand, but one Brand can have multiple Vehicles.
Just flip the relationship
Schema::create('vehicles', function (Blueprint $table) { $table->id(); $table->integer('year'); $table->string('color'); $table->foreignId('brand_id')->constrained()->onUpdate('cascade')->onDelete('cascade');; $table->timestamps(); });
Foreign key should be in vehicles table
Vehicle belongs to Brand
// Models/Vehicle.php // singular, because vehicle belong only to one Brand public function brand() { return $this->belongsTo(Brand::class); }
Brand has many vehicles
// Models/Brand.php // plural because one Brand has many vehicles public function vehicles() { return $this->hasMany(Vehicle::class,'vehicles_id'); }
Then in you controller:
$vehicle = Vehicle::with('brand')->find($id); dd($vehicle->brand->name);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0