Google AMP with Laravel

Genius in trouble picture Genius in trouble · Sep 26, 2016 · Viewed 12.2k times · Source

I have recently launched an ecommerce site based on laravel. And now i really think its a good idea to implement AMP as it supports ecommerce now (even shopify and ebay are implementing it)

So my query is how can we implement AMP on laravel? Is there a way to use desktopMainTempalte.blade.php for desktop version and switch to mobileMainTemplate.blade.php on mobile version? I just don't want to create a different domain for mobile device as m.domain.com. I want something creative here but Im not sure if i am going in the right direction.

What would you guys be doing if you were in my shoe?

Answer

Mahdyfo picture Mahdyfo · Dec 19, 2018

Using different routes and controllers to do the same but with a different view is very difficult. You can do this for a better approach.

  1. Use the same web controllers for /amp/ urls
  2. View the amp pages differently by modifying view() helper

Amp Routes

To catch the /amp/ routes, add this to your RouteServiceProvider.php

protected function mapAmpRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
        'prefix' => 'amp',
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

Also change your map method:

public function map()
{
    $this->mapAmpRoutes(); // <-- Add this

    $this->mapWebRoutes();

    $this->mapApiRoutes();
}

At this time all addresses like example.com/amp/... will refer to your web.php routes.

Amp view files

Now you should customize view() helper to render a different view for amp. Create a helpers.php in app/Http directory with a view function:

function view($view = null, $data = [], $mergeData = [])
{
    $factory = app(Illuminate\Contracts\View\Factory::class);

    if (func_num_args() === 0) {
        return $factory;
    }

    //if amp, add '-amp' to view name
    if(request()->segment(1) == 'amp'){
        if(view()->exists($view . '-amp')){
            $view .= '-amp';
        }else{
            abort(404);
        }
    }
    return $factory->make($view, $data, $mergeData);
}

This function is not loaded until you add it to your bootstrap/autoload.php file

require __DIR__.'/../app/Http/helpers.php'; // <-- add this (should be before require vendor/autoload.php)
require __DIR__.'/../vendor/autoload.php';

Edit: If you don't find bootstrap/autoload.php file, search for vendor/autoload.php because laravel has removed that. (Thanks MinderMondo for the comment)

You can now add any views you like for amp with '-amp' affix. For example if you have index.blade.php the amp view name should be index-amp.blade.php.