Displaying country and capital names instead of IDs on Laravel order page

31 Views Asked by At

I have two models: Wilaya and Commune, basically like Country and Capital. There is a one-to-many relationship between the two model.

Wilaya model

class Wilaya extends Model
{
    protected $fillable = ['nom'];
    use HasFactory;

    public function communes()
    {
        return $this->hasMany(Commune::class);
    }
}

Commune model

class Commune extends Model
{
    protected $fillable = ['nom', 'wilaya_id'];
    use HasFactory;

    public function wilaya()
    {
        return $this->belongsTo(Wilaya::class);
    }
}

I want to display the WilayaName and CommuneName instead of their IDs on my order view page. Here's how I retrieve them in the controller and display them in the view.

public function show(Order $order, $id)
{
    $data = Order::find($id);
    //$data = Order::with('wilaya')->find($id);
    $arr = unserialize($data->products);
    //dd($data);

    return view('order.show', compact('data', 'arr'));
}

View

<div class="mb-3">
   <label for="exampleInputEmail1" class="form-label">Wilaya: </label>
     <input type="email" class="form-control" id="exampleInputEmail1"
       aria-describedby="emailHelp" name="email" placeholder="/"
    value="{{ $data->wilaya }}" disabled>
</div>

<div class="mb-3">
    <label for="exampleInputEmail1" class="form-label">Ville: </label>
       <input type="email" class="form-control" id="exampleInputEmail1"
         aria-describedby="emailHelp" name="email" placeholder="/"
    value="{{ $data->commune }}" disabled>
</div>

This will only display their ID Instead of Name.

I tried to fetch the name like this:

value="{{ $data->commune->name }}" and value="{{ $data->wilaya }}" and

I got an error saying:

Attempt to read property "name" on int

and I also tried to eager load the relationships on the Controller like this

$data = Order::with('wilaya.communes')->find($id);

It throws back an error, saying

Call to undefined relationship [wilaya] on model [App\Models\Order].** knowing there's no relationship between Order Model and Wilaya model nor Commune model

Feel free to tell me what I have done wrong or what I could have done better. I am new to this,.

1

There are 1 best solutions below

0
Mohmed Blida On

I have figure it out with your help and used one to many relationship

Order.php

public function wilaya()
{
    return $this->belongsTo(Wilaya::class, 'wilaya_id');
}

public function commune()
{
    return $this->belongsTo(Commune::class, 'commune_id');
}

and inside **Wilaya Model **

public function orders()
{
    return $this->hasMany(Order::class);
}

and Commune Model

public function orders()
{
    return $this->hasMany(Order::class);
}

Then I called it on the view like this:

value="{{ $data->wilaya->nom}}"
value="{{ $data->commune->nom }}"

wroks like a charm