laravel-api-crud

Laravel API CRUD with Example

Laravel API CRUD with Example

Hey guys,

In this tutorial, we will learn about a simple Laravel API CRUD.

 

Let’s say we have a Category model. We will create simple Laravel API CRUD for this model. There will be basically five methods. These are:

  1. index() method: Get all categories
  2. store() method: store /save new category to database
  3. show() method: for getting a specific  category
  4. update() method: for updating a specific category
  5. destroy() method: delete/destroy a category

In this CRUD there is no edit method, because that may/can be handled by the show() method in the frontend (consumer of the API).

 

Step 1: Create project:

For create a new project, run below command:

composer create-project laravel/laravel api-crud

or

laravel new api-crud

Step 2: Create a new database, in this case we are creating a new database called api-crud-db

laravel api crud create database

 

Step 3: Connect Database. Update your env file to connect to your database.

Step 4: Create migration file for Category. In this case, we will create Model, Controller and migration at the same time. For that we have to run below command.

php artisan make:model Category -mcr

if you run r=the above command, it will create a model file named Category.php, a controller file named CategoryController.php with all the resources for the CRUD and also a migration file named something like  2022_01_02_022759_create_categories_table.php with timestamp.

 

Step 5: in the up() function of above migration file, add below code.

$table->string('category_name');

It will create a column in categories table for category name. after that we will run our migration. To run migration, execute below command in command line.

php artisan migrate

This command will run available migration and create our Database tables with necessary columns.

Step 6: Edit the API Route file (api.php).

<?php

    use App\Http\Controllers\Api\CategoryController

    Route::apiResource('/category', CategoryController::class);

 

Step 7: Edit the Category.php model file with fillable property.

In our Category.php model file, we will add fillable property, which is “category_name“. Just add the below code in model file.

protected $fillable = ['category_name'];

Now our Model is ready, we will start working on our Controller file.

Step 8: Now in your controller file, replace the code with below code.

CategoryController.php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::all();
return response()->json($categories);
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validateData = $request->validate([
'category_name' => 'required|unique:categories|max:255',
]);

$category = new Category;
$category->category_name = $request->category_name;
$category->save();
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$category = DB::table('categories')->where('id', $id)->first();
return response()->json($category);
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$data = array();
$data['category_name'] = $request->category_name;
$user = DB::table('categories')->where('id', $id)->update($data);
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
DB::table('categories')->where('id', $id)->delete();
}
}

Here

  • index() method is used to fetch all categories from the database and return these categories as JSON response.
  • In store() method, we are validating the submitted resource. “required|unique:categories|max:255” => that means it is a required field, we are checkin the value is unique in categories table and maximum character length is 255.
  • show() method will fetch a specific category by ID filter from categories table.
  • update() function will receive an id as parameter to update the specific category. You should validate the request here also.
  • Last, destroy() method will take id as parameter to delete that specific category.

Hope you have understand the controller.

 

That’s all for today. Thank you for your concentration. See you in next one.

 

If you like this article, please checkout our others article as well.

Laravel:

PHP:

Our YouTube Channel

Editorial Staff

A Learner and trying to share what I learned!