Javatpoint Logo
Javatpoint Logo

Laravel File Upload

In this topic, we are going to see how to upload the files.

Let's understand through an example.

  • First, we create the project in laravel 5.8 by using the command given below:

composer create-project laravel/laravel=5.8 form -prefer-dist;

Laravel File Upload
  • Now, we create a model named 'Form'.
Laravel File Upload
  • Open the migration file (create_forms_table).

The above code creates a table named 'forms', which contains four columns (id, path, created_at, updated_at ).

  • Migrate the above changes in a database by using the command given below:
Laravel File Upload
  • We create a controller named 'FormController'.
Laravel File Upload
  • Now we create a view page named as form.blade.php.

form.blade.php

Storing the file in a database

In this, we will define the store() function in which we add the code of saving the file in a database.

FormController.php

In the above code, we have defined the store() function in which we store the file in $name variable, and then we move the file to the images folder. The file which we moved to the images folder is saved in a database by using the statement $data->save().

  • Now, we define a route.

Output

Laravel File Upload

When we click on the Choose File button, then we need to select the file which we want to upload. Suppose I have selected the file named as 'img.png' shown in the below screenshot:

Laravel File Upload

In the above screenshot, I have chosen the file (img.png), and then we click on the Upload button. After clicking on the Upload button, the file gets saved into the database shown in the below screenshot:

Laravel File Upload

Retrieving the data from the database

In this section, we will see how to retrieve the data from the database.

  • First, we will define the index() function in the FormController class.

FormController.php

  • In this step, we add the <img> tag.

index.blade.php

In the above code, "./images/{{$form->path}}" defines the path of the image, i.e., the image is stored in the images folder.

  • Now, we will define the route that displays the image.

Route::get('/show','FormController@index');

Output

Laravel File Upload
Laravel File Upload

In the above case, we use the static way to display the image by passing the path to the src attribute. We can also display the image without passing the name(images) of the folder in <img> tag, and this can be achieved by defining the getPathAttribute() function in the Form model.

Form.php

index.blade.php

Output

Laravel File Upload
Next TopicLaravel Sessions





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA