REST APIs (Representational State Transfer Application Programming Interfaces) are a crucial part of modern web applications, allowing different software systems to communicate with each other. In this tutorial, we will explore how to create a REST API using Laravel 11, the latest version of the popular PHP framework known for its elegant syntax and powerful features.
Before diving in, ensure you have the following installed on your system
- PHP 8.2 or higher
- Composer
- MySQL or any other supported database
- Laravel 11 (we will install this)
Step 1: Setting Up the Laravel Project
composer create-project --prefer-dist laravel/laravel RestApiDemo
Which will install laravel latest in RestApiDemo directory. Now navigate to the project directory with `cd RestApiDemo`
Step 2: Configuring the Database
DB_CONNECTION=mysqlDB_HOST=localhostDB_PORT=3306DB_DATABASE=restapidemoDB_USERNAME=*****DB_PASSWORD=*****
Now make new tables as 'customers' for save customer data as below.
php artisan make:migration create_customers_table
Which will create new db migration file `*create_customers_table.php` in `/database/migrations/` directory. open that file and create table schema in up() function as below.
public function up(): void
{
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->comment('Customer full name');
$table->string('gender')->length(50)->nullable();
$table->date('date_of_birth')->nullable();
$table->string('email')->unique();
$table->text('notes')->nullable();
$table->timestamps();
});
}
Now need create that table in database run db migration as `php artisan migrate` (verify new table customers created in database).
Step 3: Creating the Controller and Model
php artisan make:controller CustomersController --resource --model=Customer
Which will create new `CustomersController.php` in `app/Http/Controllers` directory with basic functions and `Customer.php` model in `app\Models` directory.
Update customer controller functions as below for basic CURD operation.
class CustomersController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$customers = Customer::latest()->paginate(10);
return [
"status" => 1,
"data" => $customers
];
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'date_of_birth' => 'date_format:Y-m-d',
]);
$customer = Customer::create($request->all());
return [
"status" => 1,
"data" => $customer
];
}
/**
* Display the specified resource.
*/
public function show(Customer $customer)
{
return [
"status" => 1,
"data" =>$customer
];
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Customer $customer)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'date_of_birth' => 'date_format:Y-m-d',
]);
$customer->update($request->all());
return [
"status" => 1,
"data" => $customer,
"msg" => "Customer updated successfully"
];
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Customer $customer)
{
$customer->delete();
return [
"status" => 1,
"data" => $customer,
"msg" => "Customer deleted successfully"
];
}
}
Update customer model with define database columns which needs to add or update as below.
class Customer extends Model
{
/**
* The attributes that are mass assignable.
*/
protected $fillable = [
'name',
'gender',
'date_of_birth',
'email',
'notes'
];
use HasFactory;
}
Step 4: Creating the API Routes
php artisan install:api
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomersController;
Route::resource('customers', CustomersController::class);
Step 5: Testing the API
To test the API, you can use tools like Postman or Insomnia by run `php artisan serve` (can open directly with directory URL). Here are some endpoints to test.
/api/customers
- Fetch all customers./api/customers
- Create a new customer./api/customers/{id}
- Get a single customer./api/customers/{id}
- Update an existing customer./api/customers/{id}
- Delete a customer.For create and update customer details use below JSON format send in POST/PUT request.
{
"name" : "John Doe",
"gender": "Male",
"date_of_birth": "2000-01-01",
"email": "john@deo.com",
"notes": "Test comment"
}
Creating a REST API in Laravel 11 is straightforward, thanks to its powerful built-in features. This guide covered the basics of setting up a Laravel project, configuring the database, creating models, controllers, and defining API routes. With this foundation, you can extend your API by adding more features like authentication, validation, and error handling.
For the complete source code of this project, you can visit the GitHub repository: Laravel API CRUD.