Routes

Where to find routes

Routes can be found in the folder/directory:

Sample of a route definition

Routes can contain:

"View::make(" is equivalent to "view("

Return the result of a view

Route::get('about', function() {
   return View::make('about');
});
Route::post('about', function() {
   return View::make('about');
});
Route::match(['post', 'get'], 'about', function() {
   return View::make('about');
});

This routes from: http://example.com/about

Return the result of a view, with added variables

Route::get('/', function() {
   $data = [
      'something a', 'something b', 'something c'
   ];   

   return view('welcome', compact($data));
});

This

Return the result of a controller function

Route::get('/', 'ControllerName@home');

This routes from: http://example.com/

Expecting parameters with the route

required
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});
optional

Notice the question mark after the argument in the following example.

Route::get('user/{id?}', function ($id = NULL ) {
    return 'User '.$id;
});

Regular expression constraints

Route::get('user/{name}', function ($name) {
    //
})
->where('name', '[A-Za-z]+');
Route::get('user/{id}', function ($id) {
    //
})
->where('id', '[0-9]+');
Route::get('user/{id}/{name}', function ($id, $name) {
    //
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Routing with parameters to a controller

the route
Route::get('user/{name}', 'UsersController@show');
the controller function

In the controller: UsersController

public function show($name)
{
    return 'The users name is: ' . $name;
}

Resourceful routes (REST)

Route::resource('photo', 'PhotoController');

handles:

Verb Path Action Route Name
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy
partial resources routing
Route::resource('photo', 'PhotoController',
                ['only' => ['index', 'show']]);

Route::resource('photo', 'PhotoController',
                ['except' => ['create', 'store', 'update', 'destroy']]);

Handling 404 errors

App::missing(function($exception) {
   return Response::view('error', array(), 404);
});

Showing the routes in our program

From the command prompt at the root of our application

php artisan routes
Last update: Tue, 13 Sep 2022 14:32:15