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
.