Base CSS themes Bootstrap Material Design Filled Material Design Outlined Floating Navbars, Sidebars & Footers All 74 SPA layouts AJAX Requests File uploads User account Authentication forms Roles & Permissions

File uploads: migrations & relationship
File uploads

In this tutorial, we focus on the File and MultiFile components. But note that the exact same functionalities work for the Image and MultiImage components.

Kompo stores information on file uploads in the database in 5 main attributes:

  • name: the user's original file name.
  • path: the public path for the file.
  • mime_type: the file's mime type.
  • size: the file's size in bytes.
  • id (optional - only for storing file in a single column as JSON) randomly generated unique id.

Note: You can customize the attributes' names in the kompo config file - see below.

Then depending on your desired database structure, you may use the File components with any of these methods described below:

  • As JSON in a single column or attribute.
  • HasOne / HasMany relationship
  • BelongsToMany relationship
  • MorphOne / MorphMany relationship

As JSON in a single column

In the Eloquent Model class, you have to update the `$casts` property to be able to use the file attribute as an array anywhere in your application.

In your Form class, it is straightforward. You simply use a File (or Image) component and set it's name to the `file` attribute.

When you need to use the information anywhere else in your application, you may use the `asset` helper with the file's path variable.

Note: When storing your file information as a JSON array in one of your record's columns, an additional randomly generated unique id is added to the four main attributes. This helps keeping track of deleted and re-uploaded files by the users in the Front-end.

HasOne / HasMany relationships

For this kind of relationship, you start by creating the migration for the files table. Let's assume you want to call your table `files`, your migration will have to have the 4 main attributes and an id attribute.

Then we define the relationships in our Post model. The usage is almost the same, except now the file's information are properties (instead of an array).

MorphOne / MorphMany relationship

For these relationships, we need to use `morphs` method in the migration that will generate two columns `attachable_id` for storing the ids of the parent Models and `attachable_type` for their class.

Then we define the relationships in our Post model where we need to specify the name of the morphed column - in this case 'attachable'.

Customizing file columns

You may change the names of the columns/keys used by kompo to store the file's main information. Just edit the `config/kompo.php` file and set the desired column names.