Backend Development

Creating Laravel Routes from Blade Views Using Laravel Folio

Laravel Folio and Simplifying Laravel Routing

In this post we will see how to use Laravel 10 folio package to generate laravel uri’s from blade view files.

 

 

Routing is an essential part in laravel applications, and in every day laravel projects we used to create the laravel routes ourselves in the dedicated files like routes/web.php or routes/api.php especially in big projects with many routes.

To simplify such things Laravel 10 comes with a new package called Laravel Folio. This powerful package can generate routes automatically based on your blade view files, simply by scanning a special directory called pages/ inside of views/ directory.

 

Installing Laravel Folio

Using composer you can install Laravel Folio in your Laravel 10 project:

composer require laravel/folio

After execute this command:

php artisan folio:install

The folio:install artisan command publish folio service provider and create the directory which folio will use to scan the routes or pages which is resources/views/pages.

Once executed the folio:install command you will see app/Providers/FolioServiceProvider and resources/views/pages directory created.

Note: all of your view have to be inside of resources/views/pages directory to be scanned by Folio.

Example:

Create those views:

resources/views/pages/home.blade.php

<h2>Home page</h2>

resources/views/pages/profile.blade.php

<h2>My Profile page</h2>

Assuming your project running on http://localhost:8000. The generated uri’s will be:

  • http://localhost:8000/home => for pages/home.blade.php
  • http://localhost:8000/profile => for pages/profile.blade.php

Nice, isn’t it so all we have to do create view files inside of pages/ directory without declaring them explicitly in routes/web.php.

 

In addition to this you can extend master layouts or include partial files inside of Folio pages like any normal laravel blade view:

Consider if we have this layout:

resources/views/layout/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel Folio</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />

</head>

<body class="antialiased">
<div>

    @yield('content')

</div>
</body>
</html>

Then create a new page to extend this layout:

resources/views/pages/post.blade.php

@extends('layout.app')

@section('content')
    Post page
@endsection

Now you can preview this page as we described above @ http://<base url>/post.

You can list all of the folio routes using folio:list command:

php artisan folio:list

 

 

Laravel Folio Nested Routes

You can also create nested folio page views inside of the pages/ directory and Folio will generate the appropriate routes according to the directory structure:

You can do this manually or using Folio artisan command make:folio.

php artisan make:folio categories/list

And it will be created in the pages/categories/ directory like so:

# Page [resources/views/pages/categories/list.blade.php] created successfully.

In the same way create another nested page:

php artisan make:folio categories/details

You can preview these pages according to the directory structure like so,

  • http://<base url>/categories/list
  • http://<base url>/categories/details

What about if we want to make an index page for a given directory, for instance if we visit http://<base url>/categories, it will give 404 error. However we can fix by creating an index page in this directory:

php artisan make:folio categories/index

Now visiting the page again it will work and render the categories/index.blade.php page.

This is called an index route and it renders automatically if you access the directory root if exists and it creates a laravel route internally like so:

Route::get('categories', '...');

 

Route Parameters

In addition to this Laravel Folio gives us the ability to specify route-based parameters (segments) by naming blade pages according to particular pattern:

  • [filename]: square brackets wrapping filename, like [id].blade.php

For example to access specific post using “Id” we can compose route like /posts/1 or posts/2. To achieve such route create a Folio page:

php artisan make:folio "posts/[id]"

This will create a page resources/views/pages/posts/[id].php where [id] is the filename and it will be the url segment.

To check this in the browser go to http://<base url>/posts/1 or http://<base url>/posts/1 and the id will be 1 or 2 respectively.

To catch and print the id value simply use $segmentname like:

<div>
    Post # {{$id}}
</div>
  • […filename]: To catch multiple segments, like […slug].blade.php

This is like the above pattern but this catches multiple segments by preceding three dots (…) before filename. This approach can be used in variable length url segments.

An example for this if you have a url for a product detail page like this http://<base url>/products/<id>/<slug1>/<slug2>

So let’s create this page like shown here:

php artisan make:folio "products/[...slug]"

This will create a page resources/views/pages/products/[…slug].php where […slug] is the filename and acts as the segment.

Now if you go to http://<base url>/products/22/new-product/extra-info , and will see the product detail page.

To capture the segment value in this case it will be an array using foreach or the implode() php function:

<div>
    Product # {{implode(', ', $slug)}}
</div>

 

Multiple Folio Paths in Same Laravel Application

With the support of nested routes, you can also have multiple paths in the same application. A typical use case when you have an admin panel and website in the same app.

For such cases you need to apply specific middleware for the admin and other middleware for the website.

You can accomplish this through FolioServiceProvider.

When opening app/Providers/FolioServiceProvider.php for the first time you will see this code in the boot() method:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Folio\Folio;

class FolioServiceProvider extends ServiceProvider
{
    ....
    ....


    public function boot(): void
    {
        Folio::path(resource_path('views/pages'))->middleware([
            '*' => [
                //
            ],
        ]);
    }
}

The Folio::path() method registers the directory that folio will use to scan for pages for the incoming requests. And the middleware() method allows to apply particular middlware to all or some uri’s.

So we can update this code as shown:

public function boot(): void
    {
        Folio::path(resource_path('views/pages/portal'))->uri('/');

        Folio::path(resource_path('views/pages/admin'))
                ->uri('/admin')
                ->middleware([
                    '*' => [
                                   'auth',
                                   'verified',
                                   //...
                    ],
                ]);
    }

In this code we tells laravel Folio to look for views/pages/portal and views/pages/admin directories when incoming requests comes.

Whenever accessing the base uri “/” Folio will scan the first directory /pages/portal/ and load it’s views according to the incoming http request.

While we access “/admin/*” uri’s it will scan the /pages/admin/ directory. Also i applied “auth” and “verified” middlewares to this group of routes.

After this update you can create the pages manually in any of the sub folders or you can use the make:folio command.

Example:

php artisan make:folio index

Keep in mind that when using the command it will pick the first registered directory to create the pages, in such case is views/pages/portal.

 

Assigning Route Names and Middleware

You can name the Folio routes the same way as laravel by using the name() function at the beginning of every page like so:

<?php
use function Laravel\Folio\name;

name('website.home');

?>

<div>
    Home page
</div>

You can use this named route later in links to navigate to this page:

<a href="{{ route('website.home') }}">Back home</a>

Also you can use the middleware() function to assign middleware to individual pages:

<?php
use function Laravel\Folio\middleware;

middleware(['auth', 'admin']);
?>

<div>
    Welcome to dashboard
</div>

Additionally you can apply the middleware to a group of pages as shown above in FolioServiceProvider when creating separate paths:

Folio::path(resource_path('views/pages/admin'))
                ->uri('/admin')
                ->middleware([
                    '*' => [

                    ],
                ]);

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments