Skip to content
Advertisement

Laravel: using database query in layouts page in Laravel

I have main layout page ,I want to use some database data in the navbar I did this to get data:

<?php 

    use IlluminateSupportFacadesDB;
    $my_cart = DB::table('carts')->where('user_id',Auth::user()->id)->get();
    $cart_count = $my_cart->count();
?>

the carts table has unique field course_id belonged courses table in Cart Model with method called Course() :

public function Course()
{
    return $this->belongsTo('AppModelsCourse' ,'course_id');
}

Now I want to display courses name depends on $my_cart ,I tried to use :

{{$mycart->Course->$course_name}}

But it gives me error :

Undefined property: stdClass::$Course (View: D:Wampwwwsrdemyresourcesviewslayoutsapp.blade.php)

when I use the $my_cart data it show me correctly like :

{{$mycart->course_id}}

But don’t work with Model , How can I fix this?

Advertisement

Answer

The DB class is not the Eloquent class, so does not load the Cart model, and does not have access to the relationships. You need to use the Cart class instead. If your cart model is named Cart, then you would do

$my_cart = Cart::where('user_id',Auth::user()->id)->get();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement