John Davidson

php - Calling Laravel function dynamically

0 comments
Message:


I just started learning Laravel.


I get an error message of "Error: Call to undefined function addPost()". What seems to be the problem in my code?


$command == "addPost";


use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostsController extends Controller
{
function checkPostsCommand(Request $request) {
$command = $request->btn;

$data = $this->$command($request->all());

return response()->json($data);
}
private function addPost() {
return 'wew';
}
}


My Answer:
The issue in your code is that you are trying to call a method dynamically using a variable, but you are not using the correct syntax. Instead of using `$this->$command()`, you should use `$this->{$command}()`.

Here is the corrected code:

php
$command = "addPost";
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostsController extends Controller
{
function checkPostsCommand(Request $request) {
$command = $request->btn;

$data = $this->{$command}($request->all());

return response()->json($data);
}
private function addPost() {
return 'wew';
}
}


By using curly braces around the variable name in `$this->{$command}()`, you are able to call the method dynamically based on the value of the `$command` variable.

Rate this post

3 of 5 based on 1454 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us