• Stars
    star
    774
  • Rank 58,703 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 5 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flexible Content & Repeater Fields for Laravel Nova

Laravel Nova Flexible Content

An easy & complete Flexible Field for Laravel Nova, perfect for repeated and flexible field groups.

Laravel Nova Flexible Content in action

Quick start

Here's a very condensed guide to get you started asap. See the full docs at https://whitecube.github.io/nova-flexible-content

Install

composer require whitecube/nova-flexible-content

Usage

A flexible field allows easy management of repeatable and orderable groups of fields. As opposed to the few existing solutions for Laravel Nova, this one does not have constraints on which fields you are allowed to use within these groups. That means you can use all Laravel Nova field types, and also any community-made fields.

Adding layouts

A layout represents a group of fields that can be repeated inside the Flexible field. You can add as many layouts as you wish. If only one layout is defined the field will behave like a simple Repeater and by adding more layouts you'll obtain a Flexible Content. Both concepts are similar to their cousins in Wordpress' ACF Plugin.

Layouts can be added using the following method on your Flexible fields:

 addLayout(string $title, string $name, array $fields)

The $name parameter is used to store the chosen layout in the field's value. Choose it wisely, you'll probably use it to identify the layouts in your application.

use Whitecube\NovaFlexibleContent\Flexible;

/**
 * Get the fields displayed by the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function fields(Request $request)
{
    return [
        // ...

        Flexible::make('Content')
            ->addLayout('Simple content section', 'wysiwyg', [
                Text::make('Title'),
                Markdown::make('Content')
            ])
            ->addLayout('Video section', 'video', [
                Text::make('Title'),
                Image::make('Video Thumbnail', 'thumbnail'),
                Text::make('Video ID (YouTube)', 'video'),
                Text::make('Video Caption', 'caption')
            ])
    ];
}

Example of Flexible layouts

Customizing the button label

You can change the default "Add layout" button's text like so:

Flexible::make('Content')
    ->button('Add something amazing!');

Add something amazing

Using Flexible values in views

If you are using Laravel 6 and under, or don't want to use casts, please use an accessor on your model with the HasFlexible trait.

Laravel 7 brings custom casts to the table, and flexible content fields are the perfect use case for them. The field stores its values as a single JSON string, meaning this string needs to be parsed before it can be used in your application. This can be done trivially by using the FlexibleCast class in this package:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Whitecube\NovaFlexibleContent\Value\FlexibleCast;

class MyModel extends Model
{
    protected $casts = [
        'flexible-content' => FlexibleCast::class
    ];
}

By default, the FlexibleCast class will collect basic Layout instances. If you want to map the layouts into Custom Layout instances, it is also possible. First, create a custom flexible cast by running php artisan flexible:cast MyFlexibleCast. This will create the file in the App\Casts directory.

Then easily map your custom layout classes to the proper keys:

namespace App\Casts;

class MyFlexibleCast extends FlexibleCast
{
    protected $layouts = [
        'wysiwyg' => \App\Nova\Flexible\Layouts\WysiwygLayout::class,
        'video' => \App\Nova\Flexible\Layouts\VideoLayout::class,
    ]
}

If you need more control, you can override the getLayoutMappings method instead.

The Layouts Collection

Collections returned by the FlexibleCast cast and the HasFlexible trait extend the original Illuminate\Support\Collection. These custom layout collections expose a find(string $name) method which returns the first layout having the given layout $name.

The Layout instance

Layouts are some kind of fake models. They use Laravel's HasAttributes trait, which means you can define accessors & mutators for the layout's attributes. Furthermore, it's also possible to access the Layout's properties using the following methods:

name()

Returns the layout's name.

title()

Returns the layout's title (as shown in Nova).

key()

Returns the layout's unique key (the layout's unique identifier).

Going further

When using the Flexible Content field, you'll quickly come across of some use cases where the basics described above are not enough. That's why we developed the package in an extendable way, making it possible to easily add custom behaviors and/or capabilities to Field and its output.

Custom Layout Classes

Sometimes, addLayout definitions can get quite long, or maybe you want them to be shared with other Flexible fields. The answer to this is to extract your Layout into its own class. See the docs for more information on this.

Predefined Preset Classes

In addition to reusable Layout classes, you can go a step further and create Preset classes for your Flexible fields. These allow you to reuse your whole Flexible field anywhere you want. They also make it easier to make your Flexible fields dynamic, for example if you want to add Layouts conditionally. And last but not least, they also have the added benefit of cleaning up your Nova Resource classes, if your Flexible field has a lot of addLayout definitions. See the docs for more information on this.

Custom Resolver Classes

By default, the field takes advantage of a JSON column on your model's table. In some cases, you'd really like to use this field, but for some reason a JSON attribute is just not the way to go. For example, you could want to store the values in another table (meaning you'll be using the Flexible Content field instead of a traditional BelongsToMany or HasMany field). No worries, we've got you covered!

Tell the field how to store and retrieve its content by creating your own Resolver class, which basically just contains two simple methods: get and set. See the docs for more information on this.

Usage with nova-page

Maybe you heard of one of our other packages, nova-page, which is a Nova Tool that allows to edit static pages such as an "About" page (or similar) without having to declare a model for it individually. More often than not, the Flexible Content Field comes in handy. Don't worry, both packages work well together! First create a nova page template and add a flexible content to the template's fields.

As explained in the documentation, you can access nova-page's static content in your blade views using {{ Page::get('attribute') }}. When requesting the flexible content like this, it returns a raw JSON string describing the flexible content, which is of course not very useful. Instead, you can simply implement the Whitecube\NovaFlexibleContent\Concerns\HasFlexible trait on your page Templates, which will expose the Page::flexible('attribute') facade method and will take care of the flexible content's transformation.

namespace App\Nova\Templates;

// ...
use Whitecube\NovaFlexibleContent\Concerns\HasFlexible;

class Home extends Template
{
    use HasFlexible;

    // ...
}

💖 Sponsorships

If you are reliant on this package in your production applications, consider sponsoring us! It is the best way to help us keep doing what we love to do: making great open source software.

Contributing

Feel free to suggest changes, ask for new features or fix bugs yourself. We're sure there are still a lot of improvements that could be made, and we would be very happy to merge useful pull requests.

Thanks!

Unit tests

When adding a new feature or fixing a bug, please add corresponding unit tests. The current set of tests is limited, but every unit test added will improve the quality of the package.

Run PHPUnit by calling composer test.

Made with ❤️ for open source

At Whitecube we use a lot of open source software as part of our daily work. So when we have an opportunity to give something back, we're super excited!

We hope you will enjoy this small contribution from us and would love to hear from you if you find it useful in your projects. Follow us on Twitter for more updates!

More Repositories

1

laravel-cookie-consent

Register, configure and ask for cookies consent in a EU-compliant way
PHP
276
star
2

nova-page

Static pages content management for Laravel Nova
PHP
230
star
3

php-prices

A simple PHP library for complex monetary prices management
PHP
152
star
4

laravel-timezones

Store UTC dates in the database and work with custom timezones in the application
PHP
80
star
5

lingua

A PHP-7 language codes converter, from and to the most common formats (ISO or not)
PHP
42
star
6

laravel-search-builder

A package to build fast, index-friendly search queries for Laravel
PHP
23
star
7

swipy

A lightweight JavaScript library for simple swipe gesture events
JavaScript
21
star
8

laravel-sluggable

A trait to use on your models to generate slugs based on another attribute's value. Supports translated attributes.
PHP
21
star
9

white-sass

A few SASS mixins and functions we use on daily basis
SCSS
14
star
10

nova-google-maps

A searchable google maps field that uses the Algolia Places API.
Vue
14
star
11

morpher

A lightweight JavaScript library for animating SVG shapes between several states
JavaScript
9
star
12

pluton

A javascript dispatcher that links JS classes to dom elements
JavaScript
9
star
13

laravel-prices

Manage acquisition, selling & renting prices for products and services in your Laravel Application
PHP
8
star
14

Timer

A lightweight utility to display a timer in the page and perform actions at intervals.
JavaScript
7
star
15

nova-seo

An easy to use meta, link & general SEO manager for Laravel Nova
6
star
16

winbooks-on-web-php-client

A PHP Wrapper for the Winbooks On Web REST API.
PHP
6
star
17

laravel-flexible-content

Base library for repeated layout fields, content builders and other collection components
PHP
5
star
18

Dom

A super lightweight JavaScript Dom manipulator
JavaScript
4
star
19

bem-components

Easy BEM CSS implementation for Laravel Components
PHP
4
star
20

Select

A lightweight utility to make CSS-able select dropdowns
JavaScript
4
star
21

laravel-preset

Custom Laravel Preset for the Whitecube workflow
PHP
3
star
22

nova-media-cleaner

Analyze the usage of the uploaded files inside Laravel Nova's storage directory and decide how to handle the unused ones.
PHP
2
star
23

lightbox

A simple lightbox script we use on our projects
JavaScript
1
star
24

laravel-links

Store & resolve internal URLs without having to worry about route, slug or domain changes
PHP
1
star