Good day all
I have a project that has some basic data stored inside a JSON file. I also have a function in my traits folder that can read the data and put it in an array. My problem is I don't know how to get this array from the traits through the controller and route and then use it to show data in my blade.php views.
NOTE: The route works and the functions in traits are available already.
Controller:
public function index()
{
$jsonArray=$this->read_data('genre.json');
return view('genre.index')->with('genresArray', $jsonArray );
}
Trait:
public static function read_data($json_file): mixed
{
$file_data = array();
$file_data=json_decode(file_get_contents(base_path('storage/data/'.$json_file)),true);
return $file_data;
}
View:
<?php echo $genresArray['genre']?>
jSonFile:
jSon File:
[{"genre":"Action","recordId":"8889d8017ba519b48710c1fa6cbe40b6"},
{"genre":"Romance","recordId":"8ed28b04ef0ccc3ea2caa6265c3b36ec"},
{"genre":"Sci-Fi","recordId":"85ed64f9b41d1984d4272ed6041af204"},
{"genre":"Thriller","recordId":"c0d50ced298b85a1b92748dc7f05ac47"},
{"genre":"Comedy","recordId":"3608cdef8df2b671defa5c1a5bad3f63"},
{"genre":"Family","recordId":"cc52b3c8bc56921a15592b7682b07c52"}
]
ERROR:Undefined array key "genre"
CodePudding user response:
Firstly, Import the trait to your Controller Class for example . Assuming (FileReadProcessor is the name of your trait)
use App\Utils\Traits\FileReadProcessor;
class FileReaderControllerr extends Controller{
//this is important
use FileReadProcessor;
private function index(Request $request){
return View::make('viewPage')->with('genresArray', self::read_data());
}
}
On the view, you can then access it with foreach based on the content of your file.
For instance
@foreach ($file_array as $item)
{{$item['genre']}}
{{$item['recordId']}}
@endforeach
You can echo file_array[0]['genre'] (because an array was returned) if you are sure there are element in the return value and you don't want to iterate
<?php echo $genresArray[0]['genre']?>
Please note : the mixed instance in your trait will only work on php 8.0.0 >