My problem:
I am currently trying to refactor some of my controllers. Doing so I found these two routes:
Route::get('/events', [EventsController::class, 'eventsList'])->name('event-list');
Route::get('/courses', [EventsController::class, 'allCoursesList'])->name('all-events');
they show different filter options in the frontend.
What I want to do:
Example Code:
Route::get('/courses', [
'all' => 1,
EventsController::class, 'courseList'
])->name('all-events');
so having the ability to pass a variable, in this case all
to my controller. EventsController
So I can check with if
in my controller and handle these routes differently with only one function instead of two.
With the current solutions on StackOverflow, users are using:
'uses'=>'myController@index'
now if I try it like this:
Route::get('/courses', [
'all' => 1,
'uses' => 'EventsController@CourseList'
])->name('all-events');
I get the following error:
Target class [EventsController] does not exist.
Question:
What is the current, correct way, to pass a variable to a controller, from a route. In Laravel 9 and 10.
3
Answers
You can use Route Parameters to pass variable from route to controller.
then in your controller you can access the variables
if you have multiple parameters you can pass them like so, you can use
?
for optional parameter.then in your controller you can access the variables
to access the query parameter
if the route were
/events?timeframe=0&category=1
you can access the query parameter like soLaravel versions 8 and above do not automatically apply namespace prefixes. This means that when passing the class name as a string, you need to use the fully qualified class name (FQCN).
For example:
If it makes sense for your use case, you could also use URL parameters. For example, if your
Course
models belong to aCategory
model, you might do something like this:Then in your countroller, you define the
allCoursesList
function like so:You can pass arbitrary data to the route as a parameter using the
defaults
method ofRoute
:There are also other ways of using the Route to pass data.