Laravel API CRUD with validation
CRUD refers to the operations create, read, update and delete. Follow the below instructions to create a laravel CRUD application.
Initially we are going to create a laravel project,
composer create-project laravel/laravel --prefer-dist laravelcrud
We need to update our database details in the .env file for database connectivity. Here I am going to use Mysql database. So I am providing the necessary details to connect the DB.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelcrud
DB_USERNAME=root
DB_PASSWORD=your_password
In this article, To perform the CRUD operation, we are just going to create, read, update and delete products.
Now we need to create a controller, model and migration to proceed with the CRUD operation. The below command will create all the 3(controller, model and migration) for the crud operation. In controller you will be provided with all functions that makes your job easy. For example, There will be function called store that can be used to create a record and so on.
php artisan make:model Products -mcr
The migration file which has been created will be available in the /database/migrations/migrationfilename.php. The migration file should be updated with the fields that is needed to be replicated in the database table.
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name')->unique();
$table->string('sku_id')->unique();
$table->string('hsn_code')->nullable();
$table->float('cost_price')->nullable();
$table->float('tax')->nullable();
$table->float('cess_extra')->nullable();
$table->float('sales_price');
$table->timestamps();
});
Then we need to migrate to create the database tables which is needed to perform the CRUD operations.
php artisan migrate
Once after the migration you will be able to see the tables created in your database. Since we have completed with the database creation, modal creation and controller creation. We shall move to the actual CRUD operations.
In laravel, Always the business logics will be written in the controllers. You can find the controller inside app/Http/Controllers/ProductsController.php
Follow the below procedures to create, read, update and delete the record.
Before writing all the functionality in the CRUD functions, We need to use validator in laravel. Use it in the top of the ProductsController.php file.
use Validator;
Create :
For creating a record in the database, the function store can be used.
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules=array(
'product_name' => 'required|unique:products',
'sku_id' => 'required|unique:products',
'sales_price' => 'required|numeric'
);
$messages=array(
'product_name.required' => 'Please enter a product name.',
'product_name.unique' => 'Product name should be unique.',
'sku_id.required' => 'Please enter a sku id.',
'sku_id.unique' => 'SKU Id should be unique.',
'sales_price.required' => 'Please enter a sales price.',
'sales_price.numeric' => 'Sales price must be a number'
);
$validator=Validator::make($request->all(),$rules,$messages);
if($validator->fails())
{
$messages=$validator->messages();
return response()->json(["messages"=>$messages], 500);
}$products = new Products;
$products->product_name = $request->product_name;
$products->sku_id = $request->sku_id;
$products->hsn_code = $request->hsn_code;
$products->cost_price = $request->cost_price;
$products->tax = $request->tax;
$products->cess_extra = $request->cess_extra;
$products->sales_price = $request->sales_price;
$products->save();
return response()->json(["product" => $products, "message"=>"Product has been created successfully"], 200);
}
Read :
For reading a list of records from the database, the function index can be used.
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Products::get();
return response()->json(["products" => $products], 200);
}
If a particular record is needed to be retrieved. The below code can be used,
/**
* Display the specified resource.
*
* @param \App\Models\Products $products
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$product = Products::find($id);
return response()::json(["product"=>$product]);
}
Update :
For updating the already created record the below code can be used,
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Products $products
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$rules=array(
'product_name' => 'required|unique:products',
'sku_id' => 'required|unique:products',
'sales_price' => 'required|numeric'
);
$messages=array(
'product_name.required' => 'Please enter a product name.',
'product_name.unique' => 'Product name should be unique.',
'sku_id.required' => 'Please enter a sku id.',
'sku_id.unique' => 'SKU Id should be unique.',
'sales_price.required' => 'Please enter a sales price.',
'sales_price.numeric' => 'Sales price must be a number'
);
$validator=Validator::make($request->all(),$rules,$messages);
if($validator->fails())
{
$messages=$validator->messages();
return response()->json(["messages"=>$messages], 500);
}$products = Products::find($id);
$products->product_name = $request->product_name;
$products->sku_id = $request->sku_id;
$products->hsn_code = $request->hsn_code;
$products->cost_price = $request->cost_price;
$products->tax = $request->tax;
$products->cess_extra = $request->cess_extra;
$products->sales_price = $request->sales_price;
$products->save();
return response()->json(["product" => $products, "message"=>"Product has been updated successfully"], 200);
}
Delete :
The function destroy can be used to delete a particular data from the database.
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Products $products
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product = Products::destroy($id);
return response()->json(["message" => "Product has been deleted successfully"]);
}
After writing all the functions we need to create a ‘route’ to access it as a url. All the routes should be configured in the api.php to access it as an api.
use App\Http\Controllers\ProductsController;Route::resource('products', ProductsController::class);
Use postman to check the api’s created. Please don’t forget to send data’s via raw data for PUT request alone.
That`s it !!! You have created a CRUD application.