Laravel table join and pass the value to view

Advertisements

this is my code

public function view( $sid )
    {
        $subpage = DB::table('subpages')
        ->join('categories', 'subpages.category_id', '=', 'categories.id')
        ->where('random_id', '=', $sid)
        ->get('subpages.*', 'categories.category as category_name');
        
        return view('subpage_view', compact('subpage','category_name'));
    }

and I am getting error
compact(): Undefined variable $category_name
highlighting this line

return view('subpage_view', compact('subpage','category_name'));

Not sure what I am missing here.

Note:This is in subpage controller.
I am having similar code in category Controller
and that is working just fine.

>Solution :

Because you do not have any variable named $category_name.

return view('subpage_view', compact('subpage','category_name'));

is the same as

return view('subpage_view', ['subpage' => $subpage, 'category_name' => $category_name]);

What you seek is already in the $subpage variable.

return view('subpage_view', compact('subpage'));
@foreach ($subpage as $s)
    {{ $s->category_name }}
@endforeach

Leave a Reply Cancel reply