Laravel pass array from Helper function and return the array to the Controller

Viewed 38

Hey may I know why my code is wrong. I'm trying to copy a value from Helpers function to Controllers. Here is my code in the Helper Functions.

function checkMenu(){

$menu = [
            1 => 'Cake',
            .
            .
            .
            20 => 'Butter',
];

return $menu;
}

Here is the coding in my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
.
.
.
.

class MenuController extends Controller
{
 
    $menu = checkMenu();
    
    .
    .
    .
}

I got an error which is

syntax error, unexpected '$menu' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)

And when I write it in this way

const $menu = checkMenu();

I got an error

syntax error, unexpected '$menu' (T_VARIABLE)
1 Answers

I got the solution by doing something like this

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
.
.
.
.
class MenuController extends Controller
{
 
    private $menu = []; 
    
    public function __construct()
    {
        $this->menu = checkMenu(); 
    }
.
.
.
}
Related