phpajaxlaravellaravel-blade

Call controller method in Laravel blade


I have a variable value in javascript and I need to pass it to a controller, but that controller is being loaded before the javascript file (which is called by an iframe). I'm passing the value of the javascript to the controller via ajax but when the value arrives it has already returned null the call because it is sent after the controller loads. So I made a new function to receive this amount. How this value is displayed in a pop-up after the click button. Would it be possible to call this function in a view?

Function that receives the value via js ajax.

public function level(Request $request)
    {
        $level = $request->get('level');

        return $level;
    }

I need to call this value in the view that shows the pop-up, I'm trying the code below but it doesn't work.

{!! app(App\Http\Controllers\HomeController::class)->level(app('request')) !!}

Solution

  • If this view is returned from a Controller (which it should be), call that code in the controller and pass to the view as a variable:

    public function example(Request $request){
    
      // If `public function level()` is in the current Controller
      $level = $this->level($request);
    
      // If `public function level()` is in a different Controller
      $level = app()->make(HomeController::class)->level($request);
    
      return view('your_view')->with(['level' => $level]);
    }
    

    That being said, public function level() doesn't do much... You can get the result with $request->input('level'), or request()->input('level') inside the view, etc etc.