Google AMP with Laravel
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.
- Use the same web controllers for
/amp/
urls - 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
.
There are several ways of implementing AMP pages to your web application (no matter the framework).
One example is the way https://www.theguardian.com have done this : by creating a new sumbomain "amp.theguardian.com" and every page on the main site "www.theguardian.com" has a canonical link to the same page, but the AMP version and vice versa.
Example : Normal page : LINK AMP version of the page : LINK
As you can see, they are the same, but not quite. Most of the elements that the normal page has are removed from the amp page (because AMP does not allow them or is a bad practice for AMP).
So there you have it! A way to implement AMP to your Laravel project is to have separate views (resources/views/amp) and Controller that handles them.
A good guide to what your AMP views can have as functionalities is HERE.