Home > Blockchain >  How to pass variables into different functions inside a php controller
How to pass variables into different functions inside a php controller

Time:01-31

I`m trying to create a form-select field displaying all of the schools with a specified type. The laravel functionality of the code works. As I had this on one page and it all worked fine. But I have been asked to move them on to two separate pages. And my question is how do I get my $type variable from my storeType function into my school Selection function properly? See Code :

public function schoolSelection(School $school,$type)
{
    $schools=$school->where('type','=',$type)->get();
    return view('auth.schoolSelection',compact('schools'));
}

public function storeType(Request $request, School $school)
{
    $data=$request->all();
    $type=$data['schoolType'];

    return redirect()->route('schoolSelection',compact('type'));
}

Routes :

Route::get('schoolSelection/type',[RegisteredUserController::class,'schoolType'])->name('schoolType');

Route::get('schoolSelection/school',[RegisteredUserController::class,'schoolSelection'])->name('schoolSelection');

Route::post('schoolSelection/type',[RegisteredUserController::class,'storeType'])->name('type.store');

Route::post('schoolSelection/school',[RegisteredUserController::class,'schoolSelection'])->name('schoolSelection.store');

CodePudding user response:

you can pass the $type variable to the route 'schoolSelection' by including it in the second parameter of the redirect()->route() method. You can use compact() function to pass the variables in a compact array format. Example:

return redirect()->route('schoolSelection', compact('type'));

In the schoolSelection function, you can receive the $type variable from the compact array by declaring it as a parameter in the function signature. Example:

public function storeType(Request $request, School $school)
{
    $data=$request->all();
    $type=$data['schoolType'];

    return redirect()->route('schoolSelection', ['type' => $type]);
}

And in the schoolSelection function, you can receive the passed variable as an argument:

public function schoolSelection(School $school, $type)
{
    $schools=$school->where('type','=',$type)->get();
    return view('auth.schoolSelection',compact('schools'));
}

CodePudding user response:

if both the functions are in same controller than you can make type as global variable .

class TestController extends Controller
{
    private $type;

   public function storeType(Request $request, School $school)
{
    $data=$request->all();
    $this->type=$data['schoolType'];

    return redirect()->route('schoolSelection',compact('type'));
}
   public function schoolSelection(School $school)
{
   $type = $this->$type;

    $schools=$school->where('type','=',$type)->get();
    return view('auth.schoolSelection',compact('schools'));
}
}
  • Related