
In this article, I am going to show how to create a file upload API using Laravel 8 and MySQL. API will test using Postman
- Open your project folder with a code editor.
- Open your Phpmyadmin and create a table name products, or paste the below code in SQL query
CREATE TABLE `products` (
`id` int NOT NULL,
`ProductName` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`file_path` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`description` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`price` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`updated_at` datetime NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
Once create successfully go to your code editor and create a controller and model
php artisan make:controller ProductController
php artisan make:Model Product
- Then go to your ProductController file and create a function addProduct and import Product models which
were created in the previous step - Jump on your ProductController file and paste the below code.
namespace App\Http\Controllers;
// use App\Models\File; use Validator;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
//
function addProduct(Request $req)
{
$product = new Product;
// $req->file('file')->store('products');
$product->ProductName=$req->input('name');
$product->price=$req->input('price');
$product->description=$req->input('description');
$product->file_path=$req->file('file')->store('products');
$product->save();
return $product;
}
}
Note:
$product->file_path=$req->file(‘file’)->store(‘products’); if you have not products folder then it will create folder automatically. (file) is your key
- Once create a function now you are ready to move on the api.php file under routes→api.php.Now you have to
create a Route for addProduct ProductController.php
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route ::post('/addproduct',[ProductController::class,'addProduct']);
POST method is secure for data sending. it’s not showing data on the URL
Let’s check with the postman its working or not
Thanks for reading..