Muhammad
Muhammad

Reputation: 634

How do I call a method in my controller Laravel?

I have a simple method, that is defined in my controller. I need to be able to call it from my controller

My controller code is as:

public function store(Request $request) {
    $data = $request->except('_token');

$name = "form1_sections/" . $data['nextTab'] . "_form";
parse_str($data['inputs'], $output);
$rules =  $this->call_user_func($data['currentTab']); //need to call section1() 
//here if $data['currentTab'] is section1
$validator = Validator::make($output, $rules);

if ($validator->passes()) {
    return ["view" => view("$name")->render(), "isValid" => true];
} else {
    return ["isValid" => false, "msg" => json_encode([
            'errors' => $validator->errors()->getMessages(),
            'code' => 422
        ])
    ];
}
}

function section1() {
    return [
        'startDate' => 'required| date',
        'endDate' => 'required| date|different:startDate',
        'cv' => 'mimes:pdf,doc,docx'
    ];
}
//alo have section2(), section3() etc.

$data['currentTab'] returns a string of section1() Any help is greatly appreciated.

Upvotes: 0

Views: 1772

Answers (2)

erick.macharia
erick.macharia

Reputation: 1

You should not call a controller method outside of the request/response cycle. And the schedule is made for executing commands, like the inspire command.

If you have a controller method which execute a piece of logic, put this logic in another class. Then inject this new class in the controllers action you need it and use it.

Then create a command for the task you want to want to execute. Inject the same class in the command and perform your logic using it.

Once your command works when using PHP artisan your_command_name, you can add it to the schedule: $schedule->command('your_command_name')->hourly();.

Upvotes: 0

user320487
user320487

Reputation:

Like you would in any instantiated class:

$foo = $this->section1();

Now $foo contains your returned array. You should probably denote the method as protected, as well.

Since you want to dynamically call a method based on an arbitrary string:

$foo = call_user_func('section1');

or in your case

$foo = call_user_func($data['currentTab']');

Upvotes: 1

Related Questions