How to use Backpack Fields on Non-CRUD Laravel Page

Using Backpack admin panel is always fun with its add-ons and features like Backpack Fields and various Operations, saving a lot of tim...

Karan Datwani
Karan Datwani
Share:

Using Backpack admin panel is always fun with its add-ons and features like Backpack Fields and various Operations, saving a lot of time in major projects. I wondered what if I wanted to use those backpack fields on non-crud pages; either it would lead to an unnecessary complexity or it would not work properly, but no, we can use the backpack fields on the non-crud page without much hassle.

In this tutorial, we'll explore how to integrate these fields. Let's get started:

Step 1: Create a page

Let's create a custom page where we'll add fields. This page @extends(backpack_view('blank')) to include required assets.

php artisan backpack:page PageName

Step 2: Add field

There are basically two approaches by which backpack fields can be accessed within non-crud pages.

Option A: Direct Inclusion with Blade Views At their core, Backpack fields are just Blade views, so you can load them using the blade helper @include() like:

@php
    // set the CRUD model to something (anything)
    // but ideally it'd be the model of the entity that has the form
    $crud = app()->make('crud');
    $crud->setModel(\App\Models\Monster::class);
@endphp

<h1>This is the custom non-crud page using crud field from monster class </h1>

@include('crud::fields.number', [
    'crud' => $crud,
    'field' => [
        'name' => 'price',
        'label' => 'Price',
        'type' => 'number',
        'prefix' => '$'
    ]
])

The above will output:

image

This way, you load the inputs without the overhead of a CrudController, but it has a big downside. The field definition has to be 100% correct and complete; you lose all the magic and assumption logic that Backpack usually does to make your life easier when you add fields using addField(). That’s why in most cases, I think it’s more convenient to go with a second approach.

Option B: Using Backpack’s AddField() Method Instead of manually loading each field Blade view, add them using addField(). Load all of them just like Backpack does it in the Create or Update operation:

@php
    $crud = app()->make('crud');
    $crud->setModel(\App\Models\Monster::class);
    $crud->addField([
        'label'     => "Category",
        'type'      => 'select2',
        'name'      => 'category_id',
        'entity'    => 'category',
    ]);
@endphp

<form method="post">
    @include('crud::form_content', ['fields' => $crud->fields(), 'action' => 'create'])
</form>

The above will output:

image

The benefit of this second approach is that it enables you to use Backpack fields in the same way you would in a typical CRUD operation. You can "forget" to mention stuff in the field definition. Backpack will assume it, which will help reduce the likelihood of errors. You can use fluent syntax and ensure consistency.

Step 3: Handle the Saving Process

Once you've added the fields to your non-CRUD page, you'll need to create an endpoint to handle the form submission and save the data. Since this is a custom implementation, Backpack leaves the saving logic entirely in your hands. Here's a general approach you can follow:

  1. Define a Route: Add a route in your web.php file to handle the form submission.

    Route::post('/custom-page/save', [CustomPageController::class, 'save'])->name('custom-page.save');
    
  2. Create a Controller Method: In your CustomPageController, create a method to process the form data.

    public function save(Request $request)
    {
        $validated = $request->validate([
            'price' => 'required|numeric',
            'category_id' => 'required|exists:categories,id',
        ]);
    
        // Perform the save operation
        $monster = new Monster();
        $monster->price = $validated['price'];
        $monster->category_id = $validated['category_id'];
        $monster->save();
    
        return redirect()->back()->with('success', 'Data saved successfully!');
    }
    
  3. Update the Form Action: Set the route to the form's action attribute.

    <form method="post" action="{{ route('custom-page.save') }}">
        @csrf
        @include('crud::form_content', ['fields' => $crud->fields(), 'action' => 'create'])
    </form>
    

Since you’re taking over control, the saving process is completely in your hands. You’ll need to create an endpoint to handle the form submission, retrieve the request, and process the data as per your requirements.

Conclusion

This tutorial guides on how to use Backpack fields within Non-CRUD pages. Whether using direct Blade views or the addField() method, you can achieve functionality without added complexity. To know more on this, you can visit this discussion on StackOverflow.

Thanks for reading! If you enjoyed this, consider subscribing to our newsletter for more such tutorials.

Want to receive more articles like this?

Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.

Reactions & Comments

What do you think about this?

Latest Articles

Wondering what our community has been up to?