quachtinh761
quachtinh761

Reputation: 234

[Laravel][Routing] How to pass param to controller respective with route parameter

I met a problem, although i searched many places but could not find the answer. So, i ask here for a support. I want to pass param into controller function that respective with param in route. Please see below example: I want these routes to Check controller , function getByTime($time)

Route::get('/hourly', 'Check@getByTime');
Route::get('/daily', 'Check@getByTime');
Route::get('/weekly', 'Check@getByTime');

class Check {
    function getByTime($time) {}
}

Example conditions:

hourly: $time=1
daily: $time=24
weekly: $time = 24*7

I mean like this:

Route::get('/hourly', 'Check@getByTime(1)');
Route::get('/daily', 'Check@getByTime(24)');
Route::get('/weekly', 'Check@getByTime(168)');

Please help me to resolve it. Sorry for my bad explanation, and thanks for your help.

Upvotes: 0

Views: 269

Answers (2)

Prashant Deshmukh.....
Prashant Deshmukh.....

Reputation: 2292

Not sure if I have understood your exact problem, but this will do a trick

Route::get('{slug}', function ($slug){
   if ($slug == "hourly") {
       App::call('App\Http\Controllers\Check@getByTime', [1]);
   } else if ($slug == "daily") {
       App::call('App\Http\Controllers\Check@getByTime', [24]);
   } else if ($slug == "weekly") {
       App::call('App\Http\Controllers\Check@getByTime', [168]);
   }
});

But you have add this at top of all routes.

Upvotes: 1

Vibha Chosla
Vibha Chosla

Reputation: 713

This is so simple,If you check laravel document you will find solution easily.here is the link.

By the way you can do it simply like below

Route::get('/hourly/{hour}', 'Check@getByTime');
Route::get('/daily/{day}', 'Check@getByTime');
Route::get('/weekly/{week}', 'Check@getByTime');
class Check {
    function getByTime($time) {}
}

and pass parameter in url like

http://yourhost/hourly/1
http://yourhost/daily/24
http://yourhost/weekly/168

As per your requirement you could try this:

Route::get('/hourly', 'Check@getByTime')->defaults('hour', 1);

Upvotes: 1

Related Questions