Back to blog

P6 | Creating Relational CRUD for Exercises with Craftable PRO in Laravel

Sep 13, 2024
.
Samuel Trstenský

We’ll continue building the backend for our training app by generating a CRUD for exercises and establishing a relationship between trainings and exercises. Each exercise will link to a specific training, and we’ll use Craftable PRO’s wizard mode to set up this relational CRUD.

Setting Up CRUD for Exercises

In our project, exercises have fields for title, text, duration, and a reference to the training they belong to. Similar to trainings, title and text will be translatable. To start the CRUD generation, enter the following command:

sail art craftable-pro:generate-crud exercises -w

Configuring the CRUD in Wizard Mode

  1. Listing Page Columns: We’ll display title and training_id on the listing page. Craftable PRO will replace training_id with the actual training name in the admin panel. We’ll also add training_id to our sorting options, along with id and title.
  2. Editable Fields: To make all columns editable, simply press enter when prompted.
  3. Translatable Fields: We’ll confirm that title and text are translatable by pressing enter.
  4. Media Collection: Like trainings, exercises will have a cover image. When asked about media collections, type “cover” and specify it as an image type.

Establishing the Relationship

Now, we’ll set up a relationship between exercises and trainings:

  1. Relation Type: Craftable PRO supports belongsTo and belongsToMany relationships. Since each exercise is linked to a single training, we’ll select belongsTo.
  2. Related Model: Enter Training as the related model.
  3. Foreign Key: Craftable PRO will suggest training_id as the foreign key in the exercises table, which references the trainings table. Simply press enter to confirm.
  4. Primary Column in Trainings: Select id as the primary key.
  5. Display Attribute: Choose title to represent trainings in a dropdown menu within the exercises form. This will populate the dropdown with training titles for easy selection.

Testing the Exercises Module

Preview

Head over to the admin panel to test the new 'exercises' module. You’ll see a Training dropdown in the form, allowing you to associate each exercise with a training session. Once saved, the exercise will appear in the listing, where it can be edited or deleted.

In the next video, we’ll generate a CRUD for users, using command options instead of the wizard mode, and we’ll establish a BelongsToMany relationship. See you then!