Laravel & Php

Create REST API in Laravel


laravel api

Welcome to the Laravel 8 Rest API tutorial! In this guide, I will walk you through the comprehensive steps on crafting an API using Laravel.

Laravel 8 Rest API proves invaluable when developing for mobile applications. Constructing an API with Laravel is a seamless process, thanks to the framework’s user-friendly approach.

Throughout this tutorial, we will delve into the creation of a Rest API in Laravel 8. Let’s initiate the procedure for building your API with Laravel.

Steps to Create REST API in Laravel 8:

Step 1: Install Laravel 8

composer create-project laravel/laravel:^8.0 Laravel

For the Laravel 8 REST API, first, you need to install Laravel 8 with the help of the following command

Step 2: Database configuration

The next step to creating Laravel API is database configuration. For that, add the following lines in the .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name
DB_USERNAME=here database username
DB_PASSWORD=here database password

Step 3: Create a table

The next step to make API in Laravel is to create a table. For that, use the below command

php artisan make:migration create_blogs_table

Now open the migration file and add the code given below

<?php

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

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title', 255)->nullable();
            $table->text('body')->nullable();
            $table->timestamps();
        });
    }

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

Now you have to run migration using the below command

php artisan migrate

Step 4:  Add Resource Route

For Laravel Rest API, next, we need to add a resource route for the blog crud application.

So open your “routes/api.php” file and add the following route.

use App\Http\Controllers\BlogController;Route::resource('blogs', BlogController::class);

Step 5: Add Controller and Model

To create Rest API Laravel 8, now add controller and model with the help og following command

php artisan make:controller BlogController --resource –model=Blog

After the above command, you will find a new file in the below path

“app/Http/Controllers/BlogController.php”

In this controller will create seven methods by default as given below:

  1. index()
  2. create()
  3. store()
  4. show()
  5. edit()
  6. update()
  7. destroy()

Now go to the path: app/Http/Controllers/BlogController.php

And update the code as follows

<?php

namespace App\Http\Controllers;

use App\Models\Blog;
use Illuminate\Http\Request;

class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $blogs = Blog::latest()->paginate(10);
        return [
            "status" => 1,
            "data" => $blogs
        ];
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

        $blog = Blog::create($request->all());
        return [
            "status" => 1,
            "data" => $blog
        ];
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function show(Blog $blog)
    {
        return [
            "status" => 1,
            "data" =>$blog
        ];
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function edit(Blog $blog)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Blog $blog)
    {
        $request->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

        $blog->update($request->all());

        return [
            "status" => 1,
            "data" => $blog,
            "msg" => "Blog updated successfully"
        ];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function destroy(Blog $blog)
    {
        $blog->delete();
        return [
            "status" => 1,
            "data" => $blog,
            "msg" => "Blog deleted successfully"
        ];
    }
}

Step 6: Run the CRUD application

Now the final step in Laravel 8 Rest API tutorial, you need to run the CRUD application using this command

php artisan serve

Step 7: Testing

You have successfully created Laravel Rest API. Now you can open the below URL on Postman:

1. Create Blog

url: http://127.0.0.1:8000/api/blogs

method: POST

data: { title: “Title”, body: “Body here..” }

create blog

2. Update Blog

url: http://127.0.0.1:8000/api/blogs/{id}

method: PUT/PATCH

data: { title: “Update Title”, body: “Update Body here..” }

update blog

3. Get All Blogs

url: http://127.0.0.1:8000/api/blogs/

method: GET

get all blogs

4. Get Single Blog

url: http://127.0.0.1:8000/api/blogs/{id}

method: GET

5. Delete Blog

url: http://127.0.0.1:8000/api/blogs/{id}

method: DELETE


Laravel
Share with Friends

Like this chef? Share with friends..