Joint Dots LLC

Engineering Digital Solutiosn for your Businesses

Information

Follow Us

Create restful API using Laravel

Joint Dots > How-To Guides > Create restful API using Laravel
39 Minute

Create restful API using Laravel

Introduction:

Since you are reading this tutorial, it means you already have heard about API development with Laravel a PHP framework and have decided to improve your skills on back-end development. This article will be the first on this series and before we go one with course we will assume that you have some basic knowledge on web development (HTML, CSS), now about the server client concepts with request methods and life cycle, also it is preferable to have some experience with PHP and relational databases such as MySql, even though mostly we will cover step by step if you are a complete beginner than I suggest you learn some basic development than continue over here. With that out of the way we will continue our journey together, and hope it will be fun and informational.

Requirements:

Before we will begin with details as it is customary with every CS/Development project first we will set up our goals. In this particular project we will build a mini student management system. The requirements will be as follow:

• Ability to save students data (First Name, Last Name, Birthday, Address, Department)

• Have the list of subjects (Name, Ects, Teacher)

• Which student which subject is enrolled

• Student grading

Now that we have defined our requirements, we can proceed with the actual development of the API using Laravel.

Step 1: Installing Laravel

The first step in creating our API is to install Laravel. You can do this using Composer, a dependency manager for PHP. To install Laravel, you will need to have Composer installed on your system.

To install Laravel, open a terminal window and enter the following command:

composer create-project --prefer-dist laravel/laravel student-management-api

This command will create a new Laravel project named student-management-api.

Step 2: Setting up the Database

Next, we need to set up the database for our API. Laravel comes with built-in support for several databases, including MySQL, PostgreSQL, and SQLite.

For this tutorial, we will be using MySQL. If you haven’t already, you will need to install MySQL on your system.

Once you have MySQL installed, create a new database for our project. You can do this using the MySQL command line client or a GUI tool like phpMyAdmin.

Once you have created the database, open the .env file in the root directory of your Laravel project and update the database configuration settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=student_management
DB_USERNAME=root
DB_PASSWORD=

Be sure to replace DB_DATABASE, DB_USERNAME, and DB_PASSWORD with your own values.

Step 3: Creating the Migration

Now that we have our database set up, we can create a migration to define the structure of our students, subjects, and grades tables.

To create a migration together with models, run the following command:

php artisan make:model Student -m
php artisan make:model Subject -m
php artisan make:model Grade -m

This will create models for our students, subjects, and grades tables, along with migration files.

Open each of the migration files and add the following code:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->date('birthday');
            $table->string('address');
            $table->string('department');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}; 

Migration for the subjects

 <php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('subjects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('ects');
            $table->string('teacher');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('subjects');
    }
};

p

Migration for the grades

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('grades', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('student_id')->unsigned();
            $table->integer('subject_id')->unsigned();
            $table->integer('grade');
            $table->timestamps();

            $table->foreign('student_id')->references('id')->on('students');
            $table->foreign('subject_id')->references('id')->on('subjects');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('grades');
    }
};

Step 4: Running the Migration

Now that we have defined our migration, we can run it to create the tables in our database.

To run the migration, run the following command:

php artisan migrate

This will create the students, subjects, and grades tables in your database.

Step 5: Creating the Models

Now that we have our tables created in the database, we can create models to interact with them. Next, open each of the model files and add the following code:

 namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Student extends Model
{
    use HasFactory;


    protected $fillable = [
        'first_name',
        'last_name',
        'birthday',
        'address',
        'department',
    ];


    public function grades()
    {
        return $this->hasMany(Grade::class);
    }
}


class Subject extends Model
{
    use HasFactory;


    protected $fillable = [
        'name',
        'ects',
        'teacher',
    ];


    public function grades()
    {
        return $this->hasMany(Grade::class);
    }
}


class Grade extends Model
{
    use HasFactory;


    protected $fillable = [
        'student_id',
        'subject_id',
        'grade',
    ];


    public function student()
    {
        return $this->belongsTo(Student::class);
    }


    public function subject()
    {
        return $this->belongsTo(Subject::class);
    }
} 

This code defines the structure of our models and their relationships with each other.

Step 6: Creating the Controllers

Now that we have our models set up, we can create controllers to handle the requests to our API.

To create a controller, run the following command:

php artisan make:controller API/StudentController 
php artisan make:controller API/SubjectController 
php artisan make:controller API/GradeController 

This will create controllers for our students, subjects, and grades models.

Open each of the controller files and add the following code:

Students Controller

namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Models\Student;
use App\Http\Controllers\Controller;

class StudentController extends Controller
{
    public function index()
    {
        $students = Student::all();


        return response()->json([
            'data' => $students,
        ]);
    }


    public function show(Student $student)
    {
        return response()->json([
            'data' => $student,
        ]);
    }


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


        return response()->json([
            'data' => $student,
        ], 201);
    }


    public function update(Request $request, Student $student)
    {
        $student->update($request->all());


        return response()->json([
            'data' => $student,
        ]);
    }


    public function destroy(Student $student)
    {
        $student->delete();


        return response()->json([
            'message' => 'Student deleted',
        ]);
    }
} 

Subjects controller

<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Subject;


class SubjectController extends Controller
{
    public function index()
    {
        $subjects = Subject::all();
        return response()->json($subjects);
    }


    public function show($id)
    {
        $subject = Subject::find($id);
        return response()->json($subject);
    }


    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'ects' => 'required|numeric|min:1|max:10',
            'teacher' => 'required|string|max:255',
        ]);


        $subject = Subject::create($validatedData);


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


    public function update(Request $request, $id)
    {
        $subject = Subject::find($id);


        if (!$subject) {
            return response()->json(['message' => 'Subject not found'], 404);
        }


        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'ects' => 'required|numeric|min:1|max:10',
            'teacher' => 'required|string|max:255',
        ]);


        $subject->update($validatedData);


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


    public function destroy($id)
    {
        $subject = Subject::find($id);


        if (!$subject) {
            return response()->json(['message' => 'Subject not found'], 404);
        }


        $subject->delete();


        return response()->json(['message' => 'Subject deleted'], 204);
    }
} 

Grades Controller

<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Grade;
use App\Models\Student;
use App\Models\Subject;


class GradesController extends Controller
{
    public function index()
    {
        $grades = Grade::all();
        return response()->json($grades);
    }


    public function show($id)
    {
        $grade = Grade::find($id);
        return response()->json($grade);
    }


    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'student_id' => 'required|exists:students,id',
            'subject_id' => 'required|exists:subjects,id',
            'grade' => 'required|numeric|min:1|max:10',
        ]);


        $grade = Grade::create($validatedData);


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


    public function update(Request $request, $id)
    {
        $grade = Grade::find($id);


        if (!$grade) {
            return response()->json(['message' => 'Grade not found'], 404);
        }


        $validatedData = $request->validate([
            'student_id' => 'required|exists:students,id',
            'subject_id' => 'required|exists:subjects,id',
            'grade' => 'required|numeric|min:1|max:10',
        ]);


        $grade->update($validatedData);


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


    public function destroy($id)
    {
        $grade = Grade::find($id);


        if (!$grade) {
            return response()->json(['message' => 'Grade not found'], 404);
        }


        $grade->delete();


        return response()->json(['message' => 'Grade deleted'], 204);
    }
} 

Step 7: Creating the Routes

Now that we have our controllers set up, we can create the routes to map incoming requests to the appropriate controller functions.

Open the routes/api.php file and add the following code:

use App\Http\Controllers\StudentController;
use App\Http\Controllers\SubjectController;
use App\Http\Controllers\GradeController;

Route::group(['prefix' => 'students'], function () {
    Route::get('/', [StudentController::class, 'index']);
    Route::get('/{student}', [StudentController::class, 'show']);
    Route::post('/', [StudentController::class, 'store']);
    Route::put('/{student}', [StudentController::class, 'update']);
    Route::delete('/{student}', [StudentController::class, 'destroy']);
});

Route::group(['prefix' => 'subjects'], function () {
    Route::get('/', [SubjectController::class, 'index']);
    Route::get('/{subject}', [SubjectController::class, 'show']);
    Route::post('/', [SubjectController::class, 'store']);
    Route::put('/{subject}', [SubjectController::class, 'update']);
    Route::delete('/{subject}', [SubjectController::class, 'destroy']);
});

Route::group(['prefix' => 'grades'], function () {
    Route::get('/', [GradeController::class, 'index']);
    Route::get('/{grade}', [GradeController::class, 'show']);
    Route::post('/', [GradeController::class, 'store']);
    Route::put('/{grade}', [GradeController::class, 'update']);
    Route::delete('/{grade}', [GradeController::class, 'destroy']);
});

This code defines the routes for our students, subjects, and grades resources. It maps incoming requests to the appropriate controller functions. Certaninly on the routes you could use resource api instead of group and separate routing but for the demonstrative reason I decided to display in this form which will give the same results.

Step 8: Testing the API

We’re now ready to test our API! You can use a tool like Postman to send requests to the API endpoints we defined earlier.

For example, to create a new student, you can send a POST request to http://localhost/api/students with the following data in the request body:

 {
   "first_name": "Filon",
    "last_name": "Fistyki",
    "birthday": "1990-01-01",
    "address": "123 Main St",
    "department": "Computer Science"
}

You should receive a response similar to the following:

 {
  "data": {
        "id": 1,
        "first_name": "Filon",
        "last_name": "Fistyki",
        "birthday": "1990-01-01",
        "address": "123 Main St",
        "department": "Computer Science",
        "created_at": "2023-04-30T17:26:55.000000Z",
        "updated_at": "2023-04-30T17:26:55.000000Z"
    }
}

Postman example:

No alt text provided for this image

You can also send GET, PUT, and DELETE requests to the appropriate endpoints to retrieve, update, or delete data.

Conclusion:

In this tutorial, we went through the steps of creating a basic RESTful API using Laravel. We covered setting up the database, creating models, controllers, and routes, and testing the API with a tool like Postman. As with all tutorials in this series the final code will be published in the GitHub.

This is just the beginning, there’s much more to explore and learn about Laravel’s API development capabilities. With this foundation, you can now build more complex APIs with Laravel and integrate them into your web applications. Happy coding!

Tagged with :

Leave a Reply

Your email address will not be published. Required fields are marked *