9

I'm trying to create a route in Laravel 5.1 that will search the records base on "keyword". I like to include a ? in my url for more readability. The problem is that when I'm including the ? and test the route with postman it returns nothing. But when I remove the ? and replaced it with / and test it with postman again it will return the value of keyword. Does Laravel route supports ??

//Routes.php
Route::get('/search?keyword={keyword}', [
    'as' => 'getAllSearchPublications', 
    'uses' => 'PublicationController@index'
]);

//Publication Controller
public function index($keyword)
{
    return $keyword;
}

I've been searching the internet for hours now and I've read the Laravel documentation, But I can't find the answer. Thank you.

Abdullah
  • 603
  • 3
  • 8
  • 19
  • I need to satisfy communicating with a legacy API calls that send a parameter. E.g. /customer/?id=1 Can't figure out how to do it. Did you ever get it working? – gcman105 Apr 04 '19 at 17:21

2 Answers2

16

I believe you are talking about query strings. To accept query parameters, you don't pass it as an argument. So, for example, your route should look more plain like this:

Route::get('/search', [
    'as' => 'getAllSearchPublications', 
    'uses' => 'PublicationController@index'
]);

Note: I dropped ?keyword={keyword}.

Then, in your controller method, you can grab the query parameter by calling the query method on your Request object.

public function index(Request $request)
{
    return $request->query('keyword');
}

If you didn't already, you will need to import use Illuminate\Http\Request; to use the Request class.

Thomas Kim
  • 15,326
  • 2
  • 52
  • 42
  • 1
    So what is this "as"? What purpose does it serve? And what is this "getAllSearchPublication"? And what is this "keywords"? I have a domain.com/something/?myquerystring And I need to get that myquerystring. That is the oembed convention to use domain/oembed/?something with the questionmark – Nils Riga Sep 28 '20 at 14:26
-1

Use

$resquest

Parameter in your controller action to get the query parameter. Instead of using "?" to create in your route.

Mostafiz
  • 7,243
  • 3
  • 28
  • 42