Laravel Tutorial · Laravel Basics · Lesson 3 of 27

Laravel Routing

Define routes for each HTTP method, name them, group them with prefixes, and return strings, arrays or responses.

Create a free account to save this page, take notes and track your progress. Sign in

Route methods

Laravel has a route method for each HTTP verb: Route::get, post, put, patch, delete, and match / any for several at once. The handler can be a closure or a controller method.

What you return becomes the response:

  • a string → an HTML/text response,
  • an array or Eloquent model → JSON,
  • a response object → full control over status and headers.
Routes for each HTTP method
<?php
use Illuminate\Support\Facades\Route;

Route::get('/hello', fn () => 'Hello!');
Route::get('/status', fn () => ['ok' => true, 'version' => 1]);
Route::post('/messages', fn () => response('Saved', 201)->header('X-Message-Id', '42'));
Route::delete('/messages/{id}', fn () => response()->noContent());

visit('GET', '/hello');
visit('GET', '/status');
$response = visit('POST', '/messages');
echo 'X-Message-Id: ', $response->headers->get('X-Message-Id'), "\n";
visit('DELETE', '/messages/42');
visit('PUT', '/hello');           // a method that isn't defined for this URL

Output

GET /hello -> 200 Hello!
GET /status -> 200 {"ok":true,"version":1}
POST /messages -> 201 Saved
X-Message-Id: 42
DELETE /messages/42 -> 204
PUT /hello -> 405 {
    "message": "The PUT method is not supported for route hello. Supported methods: GET, HEAD."
}

Run this on your computer — see “Get Started” for setup.

Named routes and groups

Give routes names with ->name('posts.show') and generate URLs with route('posts.show', ['id' => 5]), so changing a URL doesn't break links. Groups share a prefix, a name prefix or middleware.

Named routes and groups
<?php
use Illuminate\Support\Facades\Route;

Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('/users', fn () => 'All users')->name('users.index');
    Route::get('/users/{id}', fn (string $id) => "User $id")->name('users.show');
});

visit('GET', '/admin/users/7');
echo route('admin.users.index'), "\n";
echo route('admin.users.show', ['id' => 7]), "\n";
echo route('admin.users.show', ['id' => 7, 'tab' => 'billing']), "\n";   // extra values become a query string

Output

GET /admin/users/7 -> 200 User 7
http://localhost/admin/users
http://localhost/admin/users/7
http://localhost/admin/users/7?tab=billing

Run this on your computer — see “Get Started” for setup.

Run php artisan route:list in a project to see every route, its name and middleware.

Test yourself

What does a route return when its handler returns a PHP array?

  1. An HTML table
  2. A JSON response
  3. A PHP serialized string
  4. An error
Show answer

Answer: A JSON response

Was this page helpful?