Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel table join and pass the value to view

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading