Parker Queen
Parker Queen

Reputation: 619

Do something if any operational parameter is set in Laravel

I am using this Route for optional parameters:

Route::get('/{place?}/{day?}', 'Weather@fetch_weather');

I want the controller to execute a code if either of the parameter is present or even if none are passed.

Here is what I am trying to do:

public function fetch_weather ($place = null, $day = null) {
    if ($place) {
        if ($day) {
            //do something with provided place and provided 1 specific day
        } else {
            //do something with provided place but with 7 days
        }
    } else {
    if ($day) {
        //do something with automatic place and provided specific day
    } else {
        //do something with automatic place and 7 days
    }
}

Now if someone provides ONE parameter, how is laravel supposed to know if it is a place or a day.

Upvotes: 1

Views: 134

Answers (1)

Alex
Alex

Reputation: 1418

So you have three options :

1) You can create three different routes :

/place/{place} calls controller@place
/day/{day} calls controller@day
/placeandday/{day}/{place} controller&placeAndDay

And each method just calls and returns your fetch_weather with the proper arguments.

2) You can put the place and day as get parameters and have them with $request->get('day') and $request->get('place')

3) You can have only one route like this :

/weather/{first_arg}/{second_arg?}

You just have to check whether the second_arg is null or not and what the format of first_arg is:

  • if first_arg is a day and second_arg null : you only have the day
  • if first_arg is not a day and second_arg null : you only have the place
  • if first_arg is a day and second_arg not null : you have the day as first_arg and the place as second_arg
  • if first_arg is not a day and second_arg not null : you have the place as first_arg and the day as second_arg

I think the 3rd one is the closest to what you want to achieve, but requires slightly more code

Upvotes: 1

Related Questions