Code | Solutions

Dive into the world of Laravel and learn how to build your first RESTful API. This guide covers installation, basic endpoint setup, database interaction with Eloquent, and a simple GET request example.

What is Laravel?

Laravel is a free, open-source PHP web framework, renowned for its elegant syntax, robust features, and developer-friendly ecosystem. It simplifies common web development tasks such as routing, database interactions, authentication, and more. Built on top of several Symfony components, Laravel follows the Model-View-Controller (MVC) architectural pattern, promoting clean, maintainable, and scalable code. For developers aiming for rapid development without sacrificing functionality or security, Laravel is the framework of choice.

Installing Laravel via Composer

Before you begin, ensure you have PHP (version 8.1 or higher is recommended) and Composer installed on your system. Composer is a dependency manager for PHP. If you haven’t already, you can download and install Composer from its official website.

Once Composer is installed, you can create a new Laravel project using the following command in your terminal:

composer create-project --prefer-dist laravel/laravel your-api-project-name

Replace your-api-project-name with your desired project directory name. Composer will download Laravel and its dependencies into this new directory.

After the process is complete, navigate into your project directory:

cd your-api-project-name

Setting up a basic API endpoint

In recent versions of Laravel, the api.php file is no longer included by default in the routes directory. This is to provide developers with more flexibility. You’ll need to create it manually and then register it in your application’s bootstrap/app.php file.

create a new file named routes/api.php and add api file into laravel app, your bootstrap/app.php look like this


use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

Let’s define a simple route that returns a JSON response. Open routes/api.php and add the following:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {
  return response()->json(['message' => 'Hello from your first API!']);
});

This code defines a GET route at the /api/hello endpoint. When accessed, it will return a JSON response with a message key.

To test this, you’ll need to start the Laravel development server. Run the following command in your terminal:

php artisan serve

<p>This will typically start the server at <code>http://127.0.0.1:8000
</code>. You can then access your API endpoint by navigating to <code>http://127.0.0.1:8000/api/hello</code> in your web browser or using a tool like Postman or curl.</p>

Using Eloquent to interact with a database

Eloquent is Laravel’s powerful ORM (Object-Relational Mapper). It allows you to interact with your database tables using PHP objects and expressive syntax. Before using Eloquent, you’ll need to configure your database connection in the .env file. Update the DB_* variables with your database credentials.

Next, you’ll typically create a Model that corresponds to your database table. For example, if you have a users table, you can create a User model:

php artisan make:model User -m

The -m flag will also create a migration file, which you can use to define the structure of your users table.

In your model (e.g., app/Models/User.php), you can define relationships and other properties.

To retrieve data from the database using Eloquent, you can use methods like all(), find($id), where(), etc. For instance, to get all users:

use App\Models\User;

$users = User::all();

A simple GET request example

Let’s create an API endpoint that retrieves a list of users from the database using Eloquent. First, ensure you have a users table in your database and have run your migrations (php artisan migrate). You might also want to seed some sample data into the table using database seeders or Tinker.

Now, open routes/api.php and add the following route:

use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

Route::get('/users', [UserController::class, 'index']);

Next, create a UserController using the following Artisan command:

php artisan make:controller Api/UserController

Open the newly created controller at app/Http/Controllers/Api/UserController.php and add the following index method:

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return response()->json($users);
    }
}

This controller method retrieves all users from the database using User::all() and returns them as a JSON response.

Restart your development server if it’s not still running (<code>php artisan serve</code>) and access http://127.0.0.1:8000/api/users in your browser or API testing tool. You should see a JSON array of your users.

Conclusion

Congratulations! You’ve taken your first steps in building a RESTful API with Laravel. This guide covered the basics of installing Laravel, setting up a simple route, interacting with a database using Eloquent, and creating a basic GET request. Laravel offers a wealth of features and tools to help you build sophisticated and scalable APIs. Explore the official Laravel documentation to learn more about routing, controllers, models, database migrations, authentication, and much more.

Are you looking for a skilled Laravel developer for your next project? I am an experienced Laravel developer based in Lahore, Punjab, Pakistan, and I am passionate about building high-quality web applications and APIs. Contact me to discuss your requirements.

Leave A Comment

Recent News