Categories: Learning

How to pass multiple data to Laravel compact method from Controller to view blade?

Hello there, welcome to the random post.

Ok, I was looking to add multiple data with compact method in Laravel from controller, here is quick example solution how I did it.

My initial code was like below in one of the controller method I was working on, skipping writing whole function code, posting down what was inside the function and how I turned it out to after on my question search on Google.

Example 1:

(returning single category data to the category.edit.blade.php)

$category = Category::findOrFail($id);
return view('category.edit', compact('category','gvd', 'parentCategories'));
Example 2:

(passing multiple data)

$category = Category::findOrFail($id);
$gvd = $this->generalViewData; //this controller property returning array data to $gvd variable, then passing to compact below

$allParentCategoryIds = Category::select('parentId')->pluck('parentId');
            
// Looping on data
foreach ($allParentCategoryIds as $pid) {
      $parentCategories = Category::select('name', 'categoryId')->where('categoryId', '=', $pid)->get();
 }

return view('category.edit', compact('category','gvd', 'parentCategories')); 

Here you could also note in case if come down here by searching about how to loop controller side in laravel? so from code example you could get the answer.

I am using Laravel 8 for current development.

Hope you find it easy and handful.

Thanks for reading & Happy Learning!

admin

Recent Posts

The Ultimate Guide to Effective Meetings

In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…

2 months ago

From Mine to Market: How Gold Is Mined, Refined, and Sold in Shops

Gold is one of the most coveted precious metals in the world, adored for its…

3 months ago

The Historical Journey of Gold: From Ancient Civilizations to Modern Times

Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…

3 months ago

How to Onboard an Intern in Small, Individual-Based Company

How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…

4 months ago