
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.
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
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
.
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.
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.
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.
Before diving deep into the AMP pages lets look at our existing code base
/** Find all posts */
Route::get('/posts', 'PostsController@getPosts');
/** Find a single post */
Route::get('/posts/{slug}', 'PostsController@findPostBySlug');
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.
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
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
$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
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.
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
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,
]);
}
As we had discussed we will be having the following view pages
index.blade.php index-amp.blade.php show.blade.php show-amp.blade.php
Once you have setup your project as I said earlier now you can test whether your normal webpages and AMP pages loads or not.
https://stackcoder.in/posts/post_url
https://stackcoder.in/amp/posts/post_url
If your developing in local environment then you can use the following ways
php artisan serve
//Regular Page
http://localhost:8000/posts/post_url
//AMP Page
http://localhost:8000/amp/posts/post_url
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
Make sure to validate your website with AMP Validator.
Hope this article helped you. Please share it with your friends.
Laravel Last Executed Query In Plain SQL Statement For Debugging
Composer Install v/s Composer Update
Firebase Cloud Messaging (FCM) Browser Web Push Notifications Using Javascript And PHP
Comment And Like System Using Disqus
Unable to prepare route [{fallbackPlaceholder}] for serialization. Uses Closure In Laravel
Client-Side Form Validation With Javascript
Create Custom 404 Page In Laravel
Detect AdBlocker With Javascript And Increase Website Ads Revenue
Plain PHP Resumable Large File Uploads In Chunks Using FlowJs