How to Creates Professional REST Api in Laravel
Last updated: November 17, 2024 By Sunil Shaw
Let’s see how we can creates professional Rest Api in laravel.
What is Laravel
Laravel is an PHP’s free open source and famous web framework, developed by Taylor Otwell to develop web application for MVC (Model View Controller) architectural patterns. It supports backend and frontend development.
Laravel is an easy-to-use open-source PHP framework for developing web projects like websites and applications. It gives features and rich library to develop backend and frontend of any web applications. There is crucial part to take decisions before going to start any project, to choose which language and library would be easy and future friendly. Being a developer i suggets to choose Laravel framework. Laravel is an cross-platform open-source php framework with huge extensive library and pre-programmed functionalities such as HTML templating, routing and authentication. Laravel is an powerful framework on Model-View-Controller(MVC) architecture.
If you want to create a professional laravel blog read my this article
What is api.php in Laravel framework?
All laravel api are defined in api.php file, which is located in routes/api.php
. api.php
is an file where we write our applications url’s to be visited by application users. There are overall 4 types of routes methods GET, PUT, POST and DELETE. In reality laravel framework maps all the requests with the help of api routes. Unquestionably all the api routes are associated with specific controller.
Create Route for Billing
Let’s create routes for user view blog and backend posts. I am going to create two routes one for blog list and one for detailed blog view.
use App\Http\Controllers\BillableController;
Route::apiResource('billable', BillableController::class);
What are Controllers in Laravel Framework and How to Use it
Controllers are an necessary features in Laravel framework. Undoubtedly a controller is c in model-view-controller(MVC), Laravel is an MVC framework. Firstly controllers are classes that contains functions and methods to handle various HTTP requests. Laravel controllers are used to handle request within the single class, and the controllers are defined in app/http/controllers
directory. Secondly most of the application logics are written in Laravel Controller. i.e. we can create as many controller as needed for our applications for making our application code to have an easy-to-understand syntax. Creating controllers automatically by using this command php artisan make:controller ControllerName
.
Create Controller for Professional Api
So let’s create a controller named BillableController.php
to display billing list.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BillableController extends Controller
{
}
Create Index Function
Create index function to show list of all the articles.
public function index()
{
$billables = Billable::all();
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item retrieved successfully',
], 200);
}
Create an Function to Read One Bill Data
public function show($id)
{
$billable = Billable::find($id);
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item retrieved successfully',
], 200);
}
Create Store Method to Post Data
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255'
]);
try {
$billable = new Billable;
$billable->name = $request->name;
$billable->save();
return response()->json([
'status' => true,
'data' => $billable,
'message' => "Billable Item added successfully",
]);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
]);
}
}
Create Update Method to Update Data
public function update(Request $request, $id)
{
$userNurseryId = auth()->user()->nursery_id;
// Retrieve the Room record by ID
$billable = Billable::find($id);
// Check if the Room record exists
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
$validatedData = $request->validate([
'name' => 'required|string|max:255'
]);
try {
$billable->update([
'name' => $validatedData['name'],
]);
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item updated successfully',
], 200);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
Create Destroy Method to Delete Data
public function destroy($id)
{
$userNurseryId = auth()->user()->nursery_id;
$billable = Billable::find($id);
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
try {
$billable->delete();
return response()->json([
'status' => true,
'message' => 'Billable Item deleted successfully',
], 200);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
here is the full code of controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\MedicalCondition;
use App\Models\Billable;
class BillableController extends Controller
{
public function index()
{
$billables = Billable::all();
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item retrieved successfully',
], 200);
}
public function show($id)
{
$billable = Billable::find($id);
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item retrieved successfully',
], 200);
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255'
]);
try {
$billable = new Billable;
$billable->name = $request->name;
$billable->save();
return response()->json([
'status' => true,
'data' => $billable,
'message' => "Billable Item added successfully",
]);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
]);
}
}
public function update(Request $request, $id)
{
$userNurseryId = auth()->user()->nursery_id;
// Retrieve the Room record by ID
$billable = Billable::find($id);
// Check if the Room record exists
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
$validatedData = $request->validate([
'name' => 'required|string|max:255'
]);
try {
$billable->update([
'name' => $validatedData['name'],
]);
return response()->json([
'status' => true,
'data' => $billable,
'message' => 'Billable Item updated successfully',
], 200);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
public function destroy($id)
{
$userNurseryId = auth()->user()->nursery_id;
$billable = Billable::find($id);
if (!$billable) {
return response()->json([
'status' => false,
'message' => 'Billable Item not found',
], 404);
}
if ($billable->nursery_id !== $userNurseryId) {
return response()->json([
'status' => false,
'message' => 'Unauthorized access',
], 403);
}
try {
$billable->delete();
return response()->json([
'status' => true,
'message' => 'Billable Item deleted successfully',
], 200);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
}
What are Models in Laravel Framework and How to Use it
A Model is an PHP class in laravel framework that represent the database table. Basically It is responsible for maintaining the data in table and giving a method to user to interact with it. Data can be updated, added, retrieved or fetching and finally deleted by this models. So, let’s consider model is an manager of your data, they gurantee the validity, accuracy and safety of your data, and You can develop an User Model in Laravel if your database contains User Table. Generally the User model would be the manager to getting user records out of the database, adding new records, updating already existing records and deleting existing records.
Identically models are written as extension to the Eloquent ORM(Object-Relational Mapping) architecture in the form of PHP classes. By enabling developers to interacts with database tables. Further if you want to make model you can manually create a PHP file in the app/Models directory or use the Command make:model
Artisan command to generates a Laravel Model automatically. In order to perform CRUD(Create, Read, Update and Delete) operations on database records, But you must have to create Model. Use all() the method on the Model, for instance to get every records from table.
Create Model
Surely now we are going to write an model Billable
to connect with database.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Billable extends Model
{
use HasFactory;
protected $table = 'billable';
protected $fillable = [
'id',
'name',
'remarks',
'comments',
'created_at',
'updated_at'
];
}
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `billable` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`remarks` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `billable` (`id`, `name`, `remarks`, `created_at`, `updated_at`) VALUES
(1, 'billable 2', NULL, '2024-11-13 02:23:09', '2024-11-13 02:24:06'),
(3, 'billable Item 3', NULL, '2024-11-13 02:24:23', '2024-11-13 02:24:23'),
(4, 'Regular Session', NULL, '2024-11-13 04:53:58', '2024-11-13 04:53:58'),
(5, 'Extra Session', NULL, '2024-11-13 04:54:10', '2024-11-13 04:54:10'),
(6, 'Miscellaneous', NULL, '2024-11-13 04:54:24', '2024-11-13 04:54:24'),
(7, 'Discount', NULL, '2024-11-13 04:54:32', '2024-11-13 04:54:32'),
(8, 'Previous Outstanding', NULL, '2024-11-13 04:54:41', '2024-11-13 04:54:41');
ALTER TABLE `billable`
ADD PRIMARY KEY (`id`);
ALTER TABLE `billable`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;
How to create dynamic slider in laravel php
About Author
I am a Web Developer, Love to write code and explain in brief. I Worked on several projects and completed in no time.
View all posts by Sunil Shaw