DEV Community

Cover image for How to make API in Laravel 9
shani singh
shani singh

Posted on

How to make API in Laravel 9

Make REST API in LARAVEL 9

Today I am going to explain how you can make REST API in Laravel 9. In this video i am going to explain about CRUD Operation using REST API.

Laravel 9 Installation.

After Installing Laravel 9 we will open the code in Editor.

Step - 1

Create a Model Post with migration.

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

Next Update The Migration file at database/migrations folder.

<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->longText('description');
            $table->timestamps();
        });
    }

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

Enter fullscreen mode Exit fullscreen mode

Next update the Model fillable property in app/models/Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'description'];
}

Enter fullscreen mode Exit fullscreen mode

Step - 2

Now Generate controller by running command

php artisan make:controller Api\\PostController --model=Post
Enter fullscreen mode Exit fullscreen mode

this command will generate the file in app/Http/Controllers/Api/PostController.php

Open the file and update the code below.

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

        return response()->json([
            'status' => true,
            'posts' => $posts
        ]);
    }

    /**
     * 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(StorePostRequest $request)
    {
        $post = Post::create($request->all());

        return response()->json([
            'status' => true,
            'message' => "Post Created successfully!",
            'post' => $post
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(StorePostRequest $request, Post $post)
    {
        $post->update($request->all());

        return response()->json([
            'status' => true,
            'message' => "Post Updated successfully!",
            'post' => $post
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();

        return response()->json([
            'status' => true,
            'message' => "Post Deleted successfully!",
        ], 200);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step - 3

Now Let's create the request to validate the data by running command below.

php artisan make:request StorePostRequest
Enter fullscreen mode Exit fullscreen mode

Now open file from app/Http/Requests/StorePostRequest.php and update the code below.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "title" => "required|max:70",
            "description" => "required"
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Step - 4

Now create the API routes in routes/api.php

<?php

use App\Http\Controllers\Api\PostController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::apiResource('posts', PostController::class);

Enter fullscreen mode Exit fullscreen mode

Now serve the application and open the URL in postman.
The results will look like.

Get POSTS

Store Post

Update Post

Delete Post

The complete Tutorial is below in the video.

If you face any issue while making REST API, please comment your query.

Thank You for Reading

Reach Out To me.
Twitter
Instagram
TechToolIndia YouTube Channel

Discussion (0)