In this tutorial you will learn about the Laravel 7 File Upload Via API Example From Scratch and its application with practical example.
In this Laravel 7 File Upload Via API Example From Scratch tutorial I’ll show you how to create file upload api in laravel. In this tutorial you will learn to create API to upload file in laravel project.
Laravel 7 File Upload Via API Example From Scratch
- Step 1: Install Laravel New App
- Step 2: Add Database Credentials
- Step 3: Generate Migration & Model
- Step 4: Create Routes For File
- Step 5: Generate Controller by Artisan
- Step 6: Run Development Server
- Step 7: Laravel Upload File Via Api Using PostMan
Step 1: Install Laravel New App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
Step 2: Add Database Credentials
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
Step 3: Generate Migration & Model
Now, in this step we will create model and migration file. Please run the following command:
This command will create one model name file and as well as one migration file for the Documents table. Then Navigate to database/migrations folder and open create_documents_table.php. Then update the following code into create_documents_table.php:
Now, run the migration to create database table using following artisan command:
Step 4: Create Route For File
After this, we need to define routes in “routes/api.php” file. Lets open “routes/api.php” file and add the following routes in it.
routes/api.php
Step 5: Generate Controller by Artisan
Now, lets create a controller named DocumentController using command given below –
Note that, This command will create a controller named DocumentController.php file.
Now app/controllers/Api folder and open DocumentController.php. Then update the following file uploading methods into your DocumentController.php file:
If you want to upload images via api instead of files in laravel. So you can change in validation rules on the controller file, as follow:
Step 6: Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –