Group multiple boolean attributes in Laravel Nova

Tutorials

May 31st, 2021

group-multiple-boolean-attributes.png

Laravel Nova comes jam-packed with an amazing list of fields. These fields are pretty smart by default, and they are suited for almost every situation. But what if you have a situation in which the UI matches your needs, but the fields handles data differently. Are you forced to create a custom field? Well, maybe not.

Customize your field

Laravel Nova's fields have a bunch of methods that lets you customize their behavior. As you can read in the docs, you can customize the way the corresponding model is hydrated by attaching a fillUsing() callback. And you can customize the way the field is resolved by attaching a resolveUsing() callback. So let's use these functions, and create our own "custom" field.

Grouping multiple booleans into a BooleanGroup

Imagine you have a Message model that represents a message that can be shown in multiple scopes, like: website, app and rss. You want to query those messages easily by their scope, so you've added 3 boolean fields: scope_website, scope_app and scope_rss.

Yes, you could have made categories and created a pivot table; but you only had these scopes, and then you remembered this was an example..

1<?php
2 
3namespace App\Nova\Resources;
4 
5use App\Nova\Resource;
6use Illuminate\Http\Request;
7use Laravel\Nova\Fields\BooleanGroup;
8 
9class MessageResource extends Resource
10{
11 // ...
12 
13 public function fields(Request $request): array
14 {
15 return [
16 BooleanGroup::make('Scopes')->options($options = [
17 'scope_website' => 'Website',
18 'scope_app' => 'Application',
19 'scope_rss' => 'RSS Feed',
20 ])
21 ];
22 }
23}

Hydrating the model attributes

Instead of adding 3 different fields to the Nova Resource we want to add a BooleanGroup of these scopes. By default, the BooleanGroup field will store its options as a JSON blob on a single attribute. To change this behavior we are going to customize the hydration of our field by calling the fillUsing method with this callback function:

1use App\Model\Message;
2use Laravel\Nova\Http\Requests\NovaRequest;
3 
4// this function goes inside ->fillUsing(...)
5function (NovaRequest $request, Message $model, string $attribute, string $requestAttribute) {
6 // Make sure the `scopes` value exists on the request.
7 if (!$request->exists($requestAttribute)) {
8 return;
9 }
10 // Decode the values because it is send as a JSON blob.
11 $values = json_decode($request[$requestAttribute], true);
12 // Hydrate the model.
13 foreach ($values as $key => $value) {
14 $model->{$key} = $value;
15 }
16}

The callback function for fillUsing() receives 4 parameters:

  • NovaReqeust $request The request object that has the POST values
  • Message $model The model we are going to hydrate
  • string $attribute The name of the attribute on the model (we are not using this in our example)
  • string $requestAttribute The name of the attribute inside the $request object that has our POST value

After making sure we posted the values, we can map al those options to their model attribute. Effectively calling something like:

1$model->scope_website = 1; // or 0

Resolving the field

Now that we actually store the booleans on the correct attributes, it's time to take a look at the resolving of the field in Nova. While the model may have scopes set, all checkboxes will be turned "off". This is because the field still tries to retrieve their values from $model->scopes; which doesn't exist. So lets fix that by adding a resolveUsing
callback.

You might have noticed we defined our field options inside a $options variable. This was intentional, because we need the keys for those options. As of this time, the resolveUsing callback doesn't have access to the field itself to retrieve those options. This is our workaround.

1// this function goes inside ->resolveUsing(...)
2function ($value, Message $model, string $attribute) use ($options) {
3 $keys = array_keys($options);
4 $values = array_map(function($value, $key) use ($model) {
5 return $model->{$key};
6 }, $options, $keys);
7 
8 return array_combine($keys, $values);
9}

The callback function for resolveUsing() receives 3 parameters:

  • mixed $value The value that Laravel Nova tried to retrieve
  • Message $model The model that provided the value
  • string $attribute The name of the attribute on the model (again, we won't be needing this)

The only thing our callback needs to do is retrieve the values for every boolean from the model, and return those values as an array. This code is a bit of a mess. It's not easy to see what is going on, and we need to use values within multiple function scopes. Let's clean this up a bit by using shorthand functions and some laravel collect magic:

1fn($value, Message $model) => collect($options)->map(fn($value, $key) => $model->{$key})

There you go, a nice one-liner that resolves the field from the correct model attributes. When you refresh your Nova page, the checkboxes should correctly indicate their status.

Bonus: make this field required

Just for fun, let's assume you need to select at least one scope. Your first instinct might be to just set ->required() on the field, but that doesn't actually work, although it will give a nice asterisk * on the form. Luckily we can also add a custom validation rule by calling the rules() method on the field.

1 $field->rules('required', function (string $attribute, $value, callable $fail) {
2 if (!array_filter(json_decode($value, true) ?? [])) {
3 return $fail(sprintf('The "%s" field must have at least one option selected.', $attribute));
4 }
5})

Setting the required rule will also add the asterisk * to the form. The callback does a quick check to see if any value was returned as true. If not; we call the $fail callable and provide the reason for failing the validation.

And that's it; a custom field, without actually building a custom field.

Filed in:

Doeke Norg

PHP developer from Groningen, the Netherlands. Works mostly with Symfony, Laravel and a sprinkle of WordPress plugins. Testing enthusiast. Recently started blogger.