Posts tagged with routing

Join thousands of developers

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages.

No spam. Unsubscribe anytime. You can also follow me on X.

Develop faster by adding dev routes file in a Laravel app

by Freek Van der Herten – 3 minute read

Laravel's awesome closure based routing was probably one of the first features I fell in love with. I take it for granted now, but back in the days, such a simple way of adding a route felt like a glass of water in hell compared to the other frameworks.

Typically, you would only add routes that are necessary for the users of your app. Something that I have been doing for a long time is to create a routes file, called dev.php, with routes that can help with app development.

Read more

A better way to register routes in Laravel

by Freek Van der Herten – 3 minute read

Let's take a look at how you can define routes to controllers in Laravel. By default you can do it like this: Route::get('my-route', 'MyController@index'); This will look for the MyController class in the App\Http\Controllers namespace. This default namespace is set up in Laravel's…

Read more

Use your Laravel named routes in JavaScript

Daniel Coulbourne, an engineer at Tighten Co and co-host of the amazing Twenty Percent Time podcast, recently released Ziggy, a tool to share your Laravel named routes with JavaScript.

Ziggy creates a Blade directive which you can include in your views. This will export a JavaScript object of your application's named routes, keyed by their names (aliases), as well as a global route() helper function which you can use to access your routes in your JavaScript.

https://github.com/tightenco/ziggy

Read more

Symfony Routing performance considerations

On his blog Frank De Jonge explains how he solved a performance problem in one of his projects.

Last week I took a deep dive into Symfony's Routing Component. A project I worked on suffered from a huge performance penalty caused by a routing mistake. This lead me on the path to discovering some interesting performance considerations. Some common practices align nicely with Symfony's optimisations, let's look into those.

https://blog.frankdejonge.nl/symfony-routing-performance-considerations/

Read more

Non-breaking, SEO Friendly Url's in Laravel

Sebastian De Deyne, author of many Spatie packages, posted a new blog article on how to generate SEO Friendly Urls in Laravel.

When admins create or update an news item—or any other entity—in our homegrown CMS, a url slug is generated based on it's title. The downside here is that when the title changes, the old url would break. On the other hand, if we wouldn't regenerate the url on updates, titles that were edited later on would still have an old slug in the url, which isn't an ideal situation either.

https://sebastiandedeyne.com/posts/2017/non-breaking-seo-friendly-urls-in-laravel

Read more

Route model binding using middleware

Our team is currently working on a Spark app. Spark makes is real easy to add an API that can be consumed by the users of the app. The generation of API tokens and authentication middleware comes out of the box. It all works really great.

In our API the a team owner can fetch information on every member on the team and himself. The url to fetch info of a user looks something like this: /users/<id-of-user>. Nothing too special. But we also want to make fetching a user's own information as easy as possible. Sure, the user could look op his own userid and then call the aforementioned url, but using something like /users/me is much nicer. In this way the user doesn't have to look op his own id. Let's make that possible.

In our app we use these functions to get the the current user and team:

/**
 * @return \App\Models\User|null
 */
function currentUser()
{
    return request()->user();
}

/**
 * @return \App\Models\Team|null
 */
function currentTeam()
{
    if (!request()->user()) {
        return;
    }

    return request()->user()->currentTeam();
}

The route look something to get the user data looks something like this:

Route::post('/users/{userId}', 'UserController@show');

My first stab to get /users/me working was to leverage route model binding. In the RouteServiceProvider I put this code:

$router->bind('userId', function ($userId) {
   if ($userId === "me") {
      return currentUser();
   }

   $user = currentTeam()->users->where('id', $userId)->first();

   abort_unless($user, 404, "There's no user on your team with id `{$id}`");

   return $user;
});

Unfortunately this does not work. When Laravel is binding route parameters the authentication has not started up yet. At this point currentUser and currentTeam will always return null.

Middleware comes to the rescue. Route-middleware is processed at a moment when authentication has started up. To make /users/me work this middleware can be used:

namespace App\Http\Middleware;

use Closure;

class BindRouteParameters
{
    public function handle($request, Closure $next)
    {
        if ($request->route()->hasParameter('userId')) {
            $id = $request->route()->parameter('userId');

            $user = $this->getUser($id);

            abort_unless($user, 404, "There's no user on your team with id `{$id}`");

            $request->route()->setParameter('userId', $user);
        }

        return $next($request);
    }

    public function getUser(string $id)
    {
        if ($id === 'me') {
            return currentUser();
        }

        return currentTeam()->users->where('id', $id)->first();
    }
}

There are two things you must do to use this middleware. First: it's route middleware so you such register it as such at the http-kernel.

// app/Http/Kernel.php

...
/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
...
'bindRouteParameters' => \App\Http\Middleware\BindRouteParameters::class,
]

Second: you must apply the middleware to certain routes. In a default Spark app you'll find all api-routes in a file at app/Http/api.php. That file starts with this line:

Route::group(['prefix' => 'api', 'middleware' => ['auth:api']], function () {
...

Just add the bindRouteParameters middleware to the group:

Route::group(['prefix' => 'api', 'middleware' => ['auth:api', 'bindRouteParameters']], function () {
...

I'm currently using the above solution in my app. You could make a solution that's more generic by checking if the parameters ends with orMe. Here's an example how that might work:

namespace App\Http\Middleware;

use Closure;

class BindCurrentUserRouteParameter
{
    public function handle($request, Closure $next)
    {
        collect($request->route()->parameters())
            ->each(function ($value, $parameterName) use ($request) {
                if (!ends_with($parameterName, 'orMe')) {
                    return;
                }

                if ($value === 'me') {
                    $request->route()->setParameter($parameterName, currentUser());
                }
            });

        return $next($request);
    }

If you have any questions about this approach or have any ideas how to make it better, let me know in the comments below.

Read more

Take a deep dive in Laravel's router

Over at Envato Tuts Matthew Machuga published a video explaining Laravel's router code. Going over Laravel's internal code (and other people's code in general) is always good method of learning new bits 'n' tricks.

In this lesson, we’ll explore the intricacies of Laravel Router. We’ll talk about the fundamentals of HTTP routing, before we go on to analyze some of the decisions and nuances in the design of Laravel Router. We’ll also talk about some of the awesome features that have been recently added to the router.
http://code.tutsplus.com/courses/how-its-made-laravel-router/lessons/how-its-made-laravel-router

Can't get enough Machuga? Then listen to the Full Stack Radio podcast, he's been a guest there several times. He's also one of the speakers of this year's Laracon US.

Read more

Redirect every request in a Laravel app

by Freek Van der Herten – 1 minute read

I recently had to redirect every single request in a Laravel app. You might think that would be as easy as this: Route::get('/', function() { return redirect('https://targetdomain.com'); }); But that'll only redirect the "/" page. All other requests will return a 404.…

Read more