3

I am trying to create a route that takes either one of two parameters. However the dd returns me $b_id, null instead of null, $b_id. How can I pass only b as a parameter and omit a?

web.php

Route::get('myroute/{a?}/{b?}', [MyController::class, 'testFunction'])
    ->name('test.testFunction');

Controller

public function testFunction( $a = null,  $b = null) 
{
    dd($a, $b);
    // stuff
}

Ajax call

function test($b_id) {
    $url = "{{ route('test.testFunction', ':b') }}";
    $url = $url.replace(":b", $b_id);
    $.ajax({
        url: $url,
        type: 'GET'
    })}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
pnonnen
  • 39
  • 1
  • 9
  • There's no practical way to differentiate between `myroute/thisisB` vs `myroute/thisisA` you need an alternative approach. Perhaps you are asking your route to do too much – apokryfos Mar 18 '22 at 11:54
  • I've found a workaround by having $url = "{{ route('test.testFunction', ['a'=>'null', 'b'=>':b']) }}"; But it makes the use of optionnal parameters pointless – pnonnen Mar 18 '22 at 12:00
  • 1
    Yeah, chaining optional parameters like that has never been supported in Laravel; unless you literally put `/null/1` in the URL (or `/0/1`, `/blank/1`, etc), Laravel has no way of knowing that you intend `1` to be `{b?}` instead of `{a?}`. Depending on what `a` and `b` are supposed to be, you might just be better of using Query String parameters, i.e. `?a=&b=1` (`$request->input('a')` would be `null`, and `$request->input('b')` would be `1`). – Tim Lewis Mar 18 '22 at 13:50

1 Answers1

2

This is not really possible at the moment but there is a workaround. You can pass the parameters in an named array and change the route to simply Route::get('myroute' ...):

route('test.testFunction', ['a' => 'xyz', 'b' => 'yzt'])
===== creates
http://myroute?a=xyz&b=yzt

Afterwards you can check if the parameters a or b are present and retrieve them normally if they are.

Aless55
  • 2,652
  • 2
  • 15
  • 26
  • This is pretty much the same as sending 'a' and 'b' in data and having testFunction(Request $request). Thanks for your answer, shame it doesn't exist yet. – pnonnen Mar 18 '22 at 13:20
  • Yes exactly, just with a GET request instead of a POST request :) – Aless55 Mar 18 '22 at 13:32