Kevin
Kevin

Reputation: 335

Laravel 7 Single row echo belongsToMany relationship

I'm trying to display the value of brand_id column from brands table. Here's so far what I've done:

Car model

use App\Brand;

class Car extends Model
{
    public function brands(){
        return $this->belongsToMany(Brand::class);
     }
}

Brand model

use App\Car;

class Brand extends Model
{
    protected $fillable = [
        'brand_name'
    ];

    public function cars(){
        return $this->hasMany(Car::class);
    }
}

ShowroomController

use App\Car;

class ShowroomController extends Controller
{
    public function details($name){
        $data = Car::where('car_name' , '=', $name)->first();

        if ($data == null){
            return redirect(route('index'));
        }else{
            return view('showroom')->with('detail', $data);
        }
    }
}

showroom view

@if (isset($detail))
  {{ $detail }} 
  {{ $detail->brands->brand_name }} //this doesn't work
@endif

Database

Brands table:

+----+------------+
| id | brand_name |
+----+------------+
|  1 | Brand1     | 
|  2 | Brand2     | 
+----+------------+

Cars table:

+----+----------+----------+
| id | car_name | brand_id |
+----+----------+----------+
|  1 | Car      |        1 |
+----+----------+----------+

I got lost on this point. Is this the right way to do the belongstomany and hasmany relationship? Thanks.

Upvotes: 0

Views: 228

Answers (2)

Kevin
Kevin

Reputation: 335

Hi I know it seems simple, thanks to @Imboom I got a hint to fix my problem. I made some changes on Car model:

  1. return $this->belongsToMany(Brand::class); to return $this->belongsTo(Brand::class)
  2. rename name function to brand
  3. Lastly, I just added 'brand_id' to specify the column in cars table.

    public function brand(){ return $this->belongsTo(Brand::class,'brand_id'); }

In ShowroomController, I changed my return statement detail to car. See the code below:

public function details($name){
    $data = Car::where('car_name' , '=', $name)->first();

    if ($data == null){
        return redirect(route('index'));
    }else{
        return view('showroom')->with('car', $data);
    }
}

Then in showroom view, $car->brand->brand_name .

        @if (isset($car))
            {{ $car->car_name }}
            {{ $car->brand->brand_name }} // Output is Brand1
        @endif

Thank you!

Upvotes: 0

lmboom
lmboom

Reputation: 189

Change
return $this->belongsToMany(Brand::class); to return $this->belongsTo(Brand::class); on the Car model

Also rename name function to brand. because car have only single brand After it you can do $detail->brand->brand_name

Upvotes: 2

Related Questions