...

Laravel 7 blog CRUD using APIs (the easy way)

Laravel is so far the best PHP framework and it is widely used all over the globe for developing small to large scale web applications. With rising trend for mobile applications and frontend technologies, APIs are the need of hour. In this post I am going to describe how you can make CRUD Apis in Laravel for a blog (from scratch).

Requirements:

-Xampp

-VS Code

-Postman

Step 1:

Open “htdocs” folder of Xampp in file explorer than write “cmd” in address bar and press “Enter” to open cmd. In the command prompt window, run the following command for creating Laravel project:

composer create-project laravel/laravel laravue-blog-local

You can change the name from “laravue-blog-local” to any other name you like. After running this command open the newly created project in “Visual Studio Code”

Step 2:

Create a MySql database using phpmyadmin and than write the credentials of database in “.env” file located in root directory for connecting db to your project.

Laravel 7 Blog CRUD APIs

Step 3:

In VS Code press “ctrl + `” to open integrated terminal and than run the following command for creating migration that will be used to create blogs table in database

php artisan make:migration blogs

Now open the blogs migration file from database/migrations directory and replace the up and down method with

public function up()

{

// blog table

Schema::create('blogs',function (Blueprint $table) {

$table->id();

$table->string('title')->unique();

$table->text('body');

$table->string('slug')->unique();

$table->timestamps();

});

}

public function down()

{

// drop blog table

 Schema::drop('blogs');

}

up() and down() are the default methods in migrations. up() method runs when “php artisan migrate” command is executed while down() method executes when we rollback migration or reset the database. 

Step 4:

Run the following command to set up tables in database:

php artisan migrate

Step 5:

In this step we will create model for our table for using eloquent ORM. This will be used for executing CRUD Operations on DB.

For this run the following command in terminal:

php artisan make:model Blogs

The above command will create Blogs.php file in app/Http folder.

Step 6:

After creating model for db handling now we will create controller that will contain the logic of response for various blog routes. Run the following in terminal:

php artisan make:controller Api/BlogsController

This command will create a php file in app/Http/Controllers/Api directory. Open that file and paste the following code in the class container:

// Create
public function create(Request $request)
{
$blog = new Blogs();
$blog->title = $request->get('title');
$blog->body = $request->get('body');
$blog->slug = Str::slug($blog->title, "-");
$duplicate_slug = Blogs::where('slug', $blog->slug)->first();
if ($duplicate_slug) {
return response()->json(
                    ["error" => "Blog already exists"]
                );
    }
    $blog->save();
    return response()->json(
            ["success" => "Blog saved successfully"]
        );
}
// Read
public function all()
{
$blogs = Blogs::orderBy('created_at', 'desc')->get();
        return response()->json(
            ["success" => $blogs]
    );
}
public function single($slug)
{
$blog = Blogs::where('slug', $slug)->first();
if (!$blog) {
        return response()->json(
           ["error" => "Blog not found"]
        );
    }
    return response()->json(
            ["success" => $blog]
        );
}
// Update
public function update(Request $request)
{
$blog_id = $request->input('blog_id');
$blog = Blogs::find($blog_id);
    if ($blog) {
        $title = $request->input('title');
        $slug = Str::slug($title);
        $duplicate = Blogs::where('slug', $slug)->first();
         if ($duplicate) {
               if ($duplicate->id != $blog_id) {
                    return response()->json(
                        ["error" => "Title already exists"]
                    );
                } else {
                    $blog->slug = $slug;
                }
         }
         $blog->title = $title;
         $blog->body = $request->input('body');
         $blog->save();
         return response()->json(
                ["success" => "Blog updated successfully"]
            );
    } else {
         return response()->json(
                ["error" => "Blog not found"]
            );
        }
}
// Delete
public function delete(Request $request, $id)
{
$blog = Blogs::find($id);
    if ($blog) {
        $blog->delete();
          return response()->json(
                ["success" => "Blog deleted successfully"]
            );
    } else {
          return response()->json(
                ["success" => "Blog not found"]
            );
    }
}

Step 7:

Now open api.php file from routes directory and write the following lines for accessing CRUD routes

// Create
Route::post('new-blog', 'Api\[email protected]');
// Read
Route::get('/all', 'Api\[email protected]'); Route::get('single/{slug}', 'Api\[email protected]');
// Update
Route::post('update', 'Api\[email protected]');
// Delete
Route::get('delete/{id}', 'Api\[email protected]');

Step 8:

This step is for testing the Restful Apis created in the previous steps. For this you will need Postman software on your system. Open the postman and test all the APIs using following settings:

-Create

Request type:

POST

URL:

http://localhost/laravue-blog-local/public/api/new-blog

Body (form-data,Bulk Edit):

title:This is title

body:This is body

-Read

Request type:

Get

URL:

http://localhost/laravue-blog-local/public/api/all

http://localhost/laravue-blog-local/public/api/single/slug-text

-Update

Request type:

POST

URL:

http://localhost/laravue-blog-local/public/api/update

Body (form-data,Bulk Edit):

title:New Title

body:New Body

blog_id:1

-Delete

Request type:

Get

URL:

http://localhost/laravue-blog-local/public/api/delete/1