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 ModelandWilaya modelnorCommune model
Feel free to tell me what I have done wrong or what I could have done better. I am new to this,.
I have figure it out with your help and used one to many relationship
Order.php
and inside **Wilaya Model **
and Commune Model
Then I called it on the view like this:
wroks like a charm