Laravel Routing

The foundation of every application.

 

  • Guides users through our app
  • Good top-level overview

 

A Basic Route

 

app/Http/routes.php

Route::get('about', function() {
    return view('about');
});

Route with Parameters

app/Http/routes.php

Route::get('@{username}', function($username) {
    return "The user is {$username}.";
});

http://example.com/@chris

outputs

The user is chris.

Optional Parameters

app/Http/routes.php

Route::get('users/{type?}', function($type = null) {

    if (is_null($type)) {

        // get all users

    } else {

        // if type exists, get that type

    }

});

Named Routes

app/Http/routes.php

Route::get('@{username}', ['as' => 'profile', function($username) {
    return view('profile');
}]);

Create a URL

$url = route('profile', ['username' => $username]);

Why Named Routes?

<a href="{{ route('profile', ['username', $username]) }}">
    {{ $username }}
</a>

What if we switch from @{username} to just {username}?

No code changes required.

Route Group: Prefix

app/Http/routes.php

Route::group([
    'prefix' => 'dashboard'
], function() {

    // dashboard routes go here

});

Route Group: Domain

app/Http/routes.php

Route::group([
    'domain' => '{username}.mysite.com'
], function() {

    // user site specific routes go here

});

Route Group: Namespacing

app/Http/routes.php

Route::group([
    'namespace' => 'Dashboard',
    'prefix'    => 'dashboard'
], function() {

    // this route is myapp.com/dashboard
    // this will use app/Http/Controllers/Dashboard/DashboardController.php
    Route::get('/', 'DashboardController@getHome');

});

Route Group: Namespacing

app/Http/routes.php


Route::get('dashboard', 'Dashboard\DashboardController@getHome');

Route Model Binding

// app/Http/routes.php
Route::get('@{user}', 'SiteController@getProfile');


// app/Http/Controllers/SiteController.php
public function getProfile(User $user) {

    // entire user object
    dd($user);
}

Current Routes

// get the full url
Request::current();
// get a section of the url
Request::segment(1);

Laravel Routing

By Chris Sevilleja

Laravel Routing

  • 460
Loading comments...

More from Chris Sevilleja