skip to Main Content

i can’t figure out why my eloquent relationship is not working.
I have the grid and details tables related (es. grid.id = details.order_id). This works for first 2 tables but not for other 2 that are almost a copy of the first.

Working relationship code :

OrderGrid model:

use HasFactory;

protected $table = 'orders_grid';

protected $fillable = [
    'user_id',
     // more data
];

public function order_detail()
{
    return $this->hasMany('AppModelsOrderDetail');
}

OrderDetail model:

    use HasFactory;

protected $table = 'orders_detail';

protected $fillable = [
    'order_id',
    // more data
];

public function order_grid()
{
    return $this->belongsTo('AppModelsOrderGrid', 'order_id', 'id');
}

In controller

$data_details = OrderDetail::where('order_id', $id)->get();

in view

$data_details->first()->order_grid->id
// so i can get the ID from the related table

enter image description here

Now i have two more very similar models which relations are not working:

OrderGrid model 2

use HasFactory;

protected $table = 'orders_grid_jde';

protected $fillable = [
    'total_order',
    // more data
];

public function detail_jde()
{
    return $this->hasMany('AppModelsOrderDetailJde');
}

OrderDetail model 2 :

    use HasFactory;

protected $table = 'orders_detail_jde';

protected $fillable = [
    'order_jde_id',
];

public function grid_jde()
{
    return $this->belongsTo('AppModelsOrderGridJde', 'order_jde_id', 'id');
}

In controller:

$data_details = OrderDetailJde::where('order_jde_id', $id)->get();

In view:

$data_details->first()->order_jde_id->id

This is not working, if i dump($data_details->first()) relations is empty array, not as in the screen shown before

Another weird behaviour on working relation: if i dump $data_details->first() in the controller i don’t see the relation, but if i do it in view it shows as in the screen.

Sorry for the long post, tried to be understandble as possible

2

Answers


  1. In the view where you have the error, you are accessing the directly to the field named order_jde_id instead of the relationship grid_jde.

    Tips:

    You should eager load the relationships if you are planning to use these in the view.

    $books = Book::with('author')->get();
    

    https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

    Login or Signup to reply.
  2. In your Controller call the relation like this:

    $data_details = OrderDetailJde::where('order_jde_id', $id)->with("grid_jde")->get();
    

    In view:
    $data_details->first()

    It will give all the detils.

    It should work now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search