How to Upload a File in Laravel Example

55

File uploading is most used functionality in web applications.

Lots of application allows the users to manipulate files to the server like – profile image, upload documents, import data, etc.

In this tutorial, I show how you can validate and upload a file in Laravel.

Contents

  1. Controller
  2. Route
  3. View

 

1. Controller

Create a new PagesController controller.

Here, create two methods –

  • index – Load index view.
  • uploadFile – This method calls on <form> submit. Read the submitted file with $request->file('file') and assign in $file.

Syntax –

Get file details ( filename,extension, temporary location,file size, and mimeType ) using methods.

Define an $valid_extension Array variable to store valid extensions.

Assing max file size 2MB in Bytes to $maxFileSize.

Check file extension if it is valid then check its file size.

If it also valid then specify upload location in $location = 'images'.

Execute $file->move($location,$filename); to store the file.

The images folder is created inside the public/ directory at the root from where you can access the uploaded files.

NOTE – Folder automatically created if it does not exist.

Completed Code


2. Route

Open routes/web.php file.

Here, define two routes –

  • uploadFile – Post type route which calls on <form> submit.

Completed Code


3. View

Create a new index.blade.php file in resources/views/ directory.

Display Session message variable value in <p> if it is set.

Create a file element and a submit button in <form >. Also, add {{ csrf_field() }} inside <form>.

Set <form > action='/uploadFile' and enctype='multipart/form-data'.

Completed Code

 

If you found this tutorial helpful then don’t forget to share.

Leave A Reply

Your email address will not be published.