This is an article discussed about how to actually done the thing specified in the title of this article. It is about how to pass an array which is generated from the controller and the pass it to a blade view template file which exist normally in Laravel web-based framework used in the development of web-based application.
The example shown to demo the activity specified in the title of the article is described as follows :
1. A blade view template file which is going to create a Technology Category for defining Technology Service Catalog available such as Technology Database Service, Technology Mail Service, etc. It is passed in the form of an array which is generated as option HTML select. Below is the content of blade view template file named create.blade.php :
<div class="form-group"> <label class="col-md-2 control-label">Parent Category</label> <div class="col-md-2"> <select> <option selected disabled>Pilih Parent Category</option> @foreach($data as $key => $technology) <option value="{{$technology['id']}}">{{$technology['name']}}</option> @endforeach </select> </div> </div>
2. As shown in the above snippet code of blade view template file, there is a variable named ‘data’. It is then furthermore, it is iterated as a variable named $technology. To be able to populate the value or the content of ‘data’, it is actually done in the controller file named ‘TechnologyCategoryController.php’. The following is the content or the snippet code intended to aim for that purpose :
public function create() { $tech_category = TechnologyCategory::all(); $data = $tech_category->toArray(); return view('technology-category.create', compact('data')); }
3. The utility provided which is used is ‘compact’. It is actually in the above snippet code takes the role for holding an array variable. The array variable retrieved by changing or converting the result acquired from executing method ‘all’ to a Model Class named ‘TechnologyCategory’. It is shown in the following line extracted from the above snippet code :
$tech_category = TechnologyCategory::all();
The result acquired is actually a variable containing object retrieved where there is a method named ‘toArray()’ attached to it. It is shown in the folowing line extracted from the above snippet code :
$data = $tech_category->toArray();
So, the variable itself will be a parameter to the reserved utility named ‘compact’ in order to be passed to a blade view template named ‘create’ located in the folder named ‘technology-create’. The snippet code is shown as follows :
return view('technology-category.create', compact('data'));
One thought on “How to Pass Array from Controller to View in Laravel using Compact”