Home > Enterprise >  Calling Laravel function dynamically
Calling Laravel function dynamically

Time:11-22

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';
    }
}

CodePudding user response:

use it like this :

$this->$command();

CodePudding user response:

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

class PostsController extends Controller
{
    function checkPostsCommand(Request $request)
    {
        $command = $request->btn;
        return $this->addPost();
    }
    private function addPost() {
        echo 'wew';
    }
}
  • Related