Laravel Reading Request Data
A request is the object that carries the data a visitor sends. It holds values from the web address, such as a search term.
Read a query value
The query method reads a value from the web address.
return $request->query('q', 'all books');The search route
The request object carries the data a visitor sends.
Route::get('/search', function (Request $request) {
return 'You searched for: ' . $request->query('q', 'all books');
});Check whether a value was sent
The has method checks whether a value was sent.
Route::get('/check', function (Request $request) {
return $request->has('q') ? 'Has search: yes' : 'Has search: no';
});Example
use Illuminate\Http\Request;
Route::get('/search', function (Request $request) {
return 'You searched for: ' . $request->query('q', 'all books');
});Key points
- Request: the object that carries the data a visitor sends to a route.
- Use $request->query('q') to read a value from the web address.
- Use a second argument, such as 'all books', as the value when q is missing.
- Use $request->has('q') to check whether a value was sent.
In this example, the route type-hints Request, so Laravel passes the request in. The action reads q from the web address. The value all books is used when q is missing. A visit to /search?q=dune shows You searched for: dune.
Note
Type-hint Request in the route closure, and Laravel passes the request in.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does $request->query('q') return for /search?q=dune?