Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Setup AMP (Accelerated Mobile Pages) To Laravel


Setup AMP (Accelerated Mobile Pages) In PHP Laravel


Share On     Share On WhatsApp     Share On LinkedIn


In this article, we will learn how to easily set up AMP (Accelerated Mobile Pages) to the Laravel project.


AMP (Accelerated Mobile Pages) is a web component framework to create lightweight website and rank your website in the SEO world.


We will cover the following topics


  1. Laravel Installation
  2. Different Implementation Ways
  3. Existing Non-AMP Website Code Overview
  4. AMP Routes (mapAmpRoutes in RouteServiceProvider.php)
  5. AMP Controllers
  6. AMP View Pages
  7. Testing
  8. Failed To Work? Clear Cache To Make It Work

Step 1 - Laravel Installation


If you already have the Laravel application skip to Step 2 else let's install the Laravel application with composer using the following command


composer create-project --prefer-dist laravel/laravel blog


The above command creates a new Laravel project with a name blog.


Step 2 - Different Implementation Ways


NOTE: For the sake of the explanation I am using my website name. Make sure to change it to yours while development.


Basically we can achieve it in 2 ways, at least as far as I know.


1. Subdomain


Create a subdomain with https://amp.stackcoder.in/post_url and make all the content available on that site and even migrate all your code.


Disadvantages

----------------

i. You might end up using 2 codebases. If you change in one code base then you have to go and update in another one too.

ii. Sometime you may forget and if you're using the same database for both then you will get errors in the production site.

iii. It may even impact your website SEO.


2. Same Domain With Prefixed Route (We will implement this)


We will create a prefixed route for this implementation which will look like the following


Normal Route - https://stackcoder.in/posts/post_url


AMP Route (Observe amp after the domain name) - https://stackcoder.in/amp/posts/post_url


Advantages

-------------

i. We will use most of the existing code base with minor changes to work with AMP.

ii. We will also use the existing web.php routes.

ii. No need to break our head on SEO optimization.


Disadvantages

----------------

i. If you modify anything on Non-AMP pages then even you have to modify in AMP pages

ii. You still have to create duplicate blade pages ie one for Non-AMP and one for AMP.


Step 3 - Existing Non-AMP Website Code Overview


Before diving deep into the AMP pages lets look at our existing code base


web.php

/** Find all posts */
Route::get('/posts', 'PostsController@getPosts');

/** Find a single post */
Route::get('/posts/{slug}', 'PostsController@findPostBySlug');


PostsController.php

public function getPosts()
{
    $posts = Post::with(['user'])
        ->published()
        ->orderByDesc('published_at')
        ->simplePaginate(10);

    return view('post.index', [
        'posts' => $posts
    ]);
}

public function findPostBySlug(string $slug)
{
    $post = Post::with(['user'])
        ->published()
        ->where(['slug' => $slug])
        ->first();

    if (!$post) {
        abort(404);
    }

    return view('post.show', [
        'post'   => $post,
    ]);
}


As have you seen its a simple controller without too much complications.


Step 4 - AMP Routes (mapAmpRoutes in RouteServiceProvider.php)


We will use the existing web.php routes to map our AMP routes.


Add the following code at the end of RouteServiceProvider.php class


App / Providers / RouteServiceProvider.php

protected function mapAmpRoutes()
{
    Route::prefix('amp') /** This line adds amp at start of URL */
        ->middleware('web')
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
}


Add the following code in map() function


App / Providers / RouteServiceProvider.php -> map()

$this->mapAmpRoutes();


Basically it will look like the following


public function map()
{
    $this->mapApiRoutes();
    $this->mapWebRoutes();
    $this->mapAmpRoutes();
}


NOTE: As I had said earlier by doing the above way our web.php routes will be reused and will look like the following


Following Web URLs & View Pages will be used from PostsController methods & view pages respectively.

https://stackcoder.in/posts        (views/post/index.blade.php)
https://stackcoder.in/amp/posts    (views/post/index-amp.blade.php)


Following Web URLs & View Pages will be used from PostsController methods & view pages respectively.

https://stackcoder.in/posts/post_url           (views/post/show.blade.php)
https://stackcoder.in/amp/posts/post_url       (views/post/show-amp.blade.php)


With the help of the above URLs, we can now easily verify which route does the current URL belongs to.


NOTE: All the amp pages will end with common view pages except -amp.blade.php

Step 5 - AMP Controllers


Important Concept - Both the routes (AMP & Non-AMP) points to the same controller methods, but from these methods, we need to decide whether the current request needs to be redirected to the AMP page or the regular page.

We will use the following code in base controller ie Controller.php so that it can be used in all the controllers with $this->getView() call.


App / Http / Controllers / Controller.php

protected function getView($view)
{
    if (request()->segment(1) == 'amp') {
        if (view()->exists($view . '-amp')) {
            $view .= '-amp';
        } else {
            abort(404);
        }
    }
    return $view;
}


And your normal PostsController.php will look like the following


Updated Controller - App / Http / Controllers / PostsController.php

public function getPosts()
{
    $posts = Post::with(['user'])
        ->published()
        ->orderByDesc('published_at')
        ->simplePaginate(10);

    /** We are using $this->getView here to decide view pages */
    return view($this->getView('post.index'), [
        'posts' => $posts
    ]);
}

public function findPostBySlug(string $slug)
{
    $post = Post::with(['user'])
        ->published()
        ->where(['slug' => $slug])
        ->first();

    if (!$post) {
        abort(404);
    }

    /** We are using $this->getView here to decide view pages */
    return view($this->getView('post.show'), [
        'post'   => $post,
    ]);
}

Step 6 - AMP View Pages


As we had discussed we will be having the following view pages


resources/views/posts/

index.blade.php
index-amp.blade.php

show.blade.php
show-amp.blade.php

Step 7 - Testing


Once you have setup your project as I said earlier now you can test whether your normal webpages and AMP pages loads or not.


Normal Pages

https://stackcoder.in/posts/post_url


AMP Pages

https://stackcoder.in/amp/posts/post_url


If your developing in local environment then you can use the following ways


Run Built In WebServer

php artisan serve


Routes

//Regular Page
http://localhost:8000/posts/post_url

//AMP Page
http://localhost:8000/amp/posts/post_url

Step 8 - Failed To Work? Clear Cache To Make It Work


Sometimes when you perform the above steps it may not reflect because of the Laravel application cache.


Please use the following commands to make it work like charm


php artisan cache:clear
php artisan route:clear
php artisan view:clear
composer dump-autoload

Conclusion


Make sure to validate your website with AMP Validator.


Hope this article helped you. Please share it with your friends.




Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing