A tutorial on building a REST API with PHP and Laravel
Tags: webdev, programming, laravel, api
Published: 2023-02-12 18:43:12

Hi there!

Representational State Transfer ([REST](https://dev.to/zhukmax/data-flow-through-services-rest-approach-5fdf)) is a popular software architecture style for building web services. REST APIs allow clients to retrieve and manipulate data from a server by making HTTP requests to specific endpoints, or "routes." In this tutorial, we will learn how to build a REST API with PHP and the Laravel framework.

[Laravel](https://habr.com/ru/company/reksoft/blog/651553/) is a popular open-source PHP framework that provides a set of tools and features for building web applications quickly and efficiently. It includes a built-in HTTP routing system, a database query builder, and a powerful task scheduler, among other things.

To get started, you will need to have PHP and Composer installed on your machine. If you don't have them already, you can download them from the official PHP and Composer websites.

Next, we will create a new Laravel project using the Laravel installer. Open a terminal and enter the following command:
```bash
composer create-project --prefer-dist laravel/laravel my-project
```
This will create a new Laravel project called "my-project" in the current directory. Once the installation is complete, navigate to the project directory and start the development server by running the following command:
```bash
php artisan serve
```
You should now be able to access your Laravel project at http://localhost:8000.

Now that we have a Laravel project set up, we can begin building our REST API. The first thing we need to do is create a model and a migration for our data. In this example, we will create a model for "tasks," which will represent a list of tasks that a user needs to complete.

To create a model and a migration, run the following command:
```bash
php artisan make:model Task -m
```
This will create a new model called "Task" and a corresponding migration file in the "database/migrations" directory. Open the migration file and modify the "up" method to create a "tasks" table with the following columns:
```php
public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description');
        $table->boolean('completed')->default(false);
        $table->timestamps();
    });
}
```
Next, run the following command to create the "tasks" table in the database:
```bash
php artisan migrate
```
With the model and migration set up, we can now create the routes for our REST API. In Laravel, routes are defined in the "routes/api.php" file. Open this file and add the following routes:
```php
Route::get('tasks', 'TaskController@index');
Route::get('tasks/{task}', 'TaskController@show');
Route::post('tasks', 'TaskController@store');
Route::put('tasks/{task}', 'TaskController@update');
Route::delete('tasks/{task}', 'TaskController@destroy');
```
These routes correspond to the following HTTP methods and endpoints:

- GET /tasks: retrieve a list of all tasks
- GET /tasks/{task}: retrieve a specific task by ID

now create the TaskController that will handle the logic for each of the routes we defined. Run the following command to generate the controller:
```bash
php artisan make:controller TaskController
```
This will create a new controller called "TaskController" in the "app/Http/Controllers" directory. Open the controller and add the following methods:
```php
public function index()
{
    return Task::all();
}

public function show(Task $task)
{
    return $task;
}

public function store(Request $request)
{
    $task = Task::create($request->all());

    return response()->json($task, 201);
}

public function update(Request $request, Task $task)
{
    $task->update($request->all());

    return response()->json($task, 200);
}

public function destroy(Task $task)
{
    $task->delete();

    return response()->json(null, 204);
}
```
These methods correspond to the routes we defined earlier. The index method returns a list of all tasks, the show method returns a specific task by ID, the store method creates a new task, the update method updates an existing task, and the destroy method deletes a task.

With the routes and controller in place, our REST API is now complete. You can test it out by making HTTP requests to the endpoints using a tool like Postman.

That's it! You have now learned how to build a REST API with PHP and Laravel. You can continue to expand on this API by adding more routes and functionality as needed. I hope this tutorial has been helpful and that you now have a good understanding of how to build a REST API with Laravel.

-----

Photo by <a href="https://unsplash.com/@lucabravo?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Luca Bravo</a> on <a href="https://unsplash.com/photos/9l_326FISzk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>