DEV Community

Cover image for A tutorial on building a REST API with PHP and Laravel
Max Zhuk
Max Zhuk

Posted on

A tutorial on building a REST API with PHP and Laravel

Hi there!

Representational State Transfer (REST) 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 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:

composer create-project --prefer-dist laravel/laravel my-project
Enter fullscreen mode Exit fullscreen mode

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:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

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:

php artisan make:model Task -m
Enter fullscreen mode Exit fullscreen mode

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:

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description');
        $table->boolean('completed')->default(false);
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Next, run the following command to create the "tasks" table in the database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

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:

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');
Enter fullscreen mode Exit fullscreen mode

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:

php artisan make:controller TaskController
Enter fullscreen mode Exit fullscreen mode

This will create a new controller called "TaskController" in the "app/Http/Controllers" directory. Open the controller and add the following methods:

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);
}
Enter fullscreen mode Exit fullscreen mode

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 Luca Bravo on Unsplash

Top comments (0)