0% found this document useful (0 votes)
27 views13 pages

Laravel 9 CRUD API Tutorial

Laravel est un framework php

Uploaded by

sokengjoys
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views13 pages

Laravel 9 CRUD API Tutorial

Laravel est un framework php

Uploaded by

sokengjoys
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

Laravel 9 REST API CRUD Tutorial


Example
Laravel saim ansari September 12, 2023

In this section we will see laravel 9 rest api crud app. For
this tutorial we will create simple but clean laravel api
crud using Request for validation, Resource for showing
important & clean data. we will create simple but clean
architecture laravel 9 api crud application.

Note: Before we will start you should have php 8.x version
in your system. Because laravel 9 support php 8 & above
php version.

Step 1: Install Laravel & Connect Database


Installing a fresh new laravel 9 application, so head over
to the terminal, type the command, and create a new
laravel app.

composer create-project laravel/laravel crud

[Link] 1/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

Now, you have to connect the laravel app to the


database, hence open the .env configuration file and
add the database credentials as suggested below.

.env

DB_CONNECTION=mysql
DB_HOST=[Link]
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

Step 2: Create Model Request and


Resource, Api Controller & route
Create Post Modal with migration

php artisan make:model Post -m

Create Post Request for validation

php artisan make:request StorePostRequest

Create Post Resource for show clean data

php artisan make:resource PostResource

Create Post Api controller

php artisan make:controller Api/PostController --mo

create_posts_table.php

[Link] 2/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

<?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->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}

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

app/Http/Models/[Link]

[Link] 3/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

<?php

namespace App\Models;

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

class Post extends Model


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

app/Http/Requests/[Link]

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest


{
/**
* Determine if the user is authorized to make
*
* @return bool
*/
public function authorize()
{
return false;
}

/**
* Get the validation rules that apply to the r
*
* @return array
*/
public function rules()
{
return [
'title' => ['required', 'max:70'],

[Link] 4/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

'description' => ['required']


];
}
}

app/Http/Controllers/Api/[Link]

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Http\Resources\PostResource;
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 PostResource::collection($posts);
}

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

/**

[Link] 5/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

* Store a newly created resource in storage.


*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StorePostRequest $request
{
$posts = Post::create($request->all());

return new PostResource($posts);


}

/**
* 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 reso
*
* @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 $reques
{
$post->update($request->all());

[Link] 6/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

return new PostResource($post);


}

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

return response(null, 204);


}
}

routes/[Link]

<?php

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

/*
|--------------------------------------------------
| API Routes
|--------------------------------------------------
|
| Here is where you can register API routes for you
| routes are loaded by the RouteServiceProvider wit
| is assigned the "api" middleware group. Enjoy bui
|
*/

Route::middleware('auth:sanctum')->get('/user', fun
return $request->user();
});

[Link] 7/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

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

run app

php artisan serve

Step 3: Test CRUD App in Postman API

POST

[Link]

GET

[Link]

[Link] 8/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

PUT

[Link]

DELETE

[Link]

[Link] 9/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

Read Also
Laravel 9 Add Simple Sidebar with Tailwind CSS Example

How to Use Carousel Slider in Laravel 9 Example

Laravel 9 Posts with Tags Many to Many Relationships


Example

Laravel 9 Insert Category in Posts CRUD Example

How to Use Ckeditor 5 in Laravel 9 Vite with Tailwind CSS

Laravel 9 Simple Image Upload in Ckeditor 5 Example

Laravel 9 Flash Message Timeout and Hide Message


Example

Install & Setup Markdown Editor in Laravel 9

Nuxt 3 Data Fetching Using Laravel 9 Api Example

Laravel 9 Image Upload with Preview using Tailwind CSS


& Alpine JS

Laravel 9 with Tailwind CSS Form Validation Example

Laravel 9 Backend Api Connect with Vue 3 Using Axios


Example

Laravel 9 Authentication with Next js Example

[Link] 10/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

Laravel 9 Sanctum Authentication with Nuxt JS Example

Laravel 9 Simple Search with Pagination Example

Laravel 9 Install Setup TALL(Tailwind, Alpinejs, Livewire)


Admin Panel

How to Fix and Clean Code Style in laravel 9

Laravel 9 Image File Upload Example

3 Way to Create Slug in Laravel 9 without Package

How to Add Dark Mode in Laravel 9 with Tailwind CSS

Tags: Laravel 9 Laravel Api

NEWSLETTER
Get updates right in your inbox. Join to get notified
with new tutorials
Enter email address

subscribe

Recent Blog

Create Cookie Consent Design UI Using Tailwind CSS

Tailwind CSS + [Link] Close Notifications Box

[Link] 11/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example
How to Use background blur in Tailwind CSS

How to Use Font Border In Tailwind CSS

Catagories

React JS

Vue JS

Livewire

Tailwind CSS

Alpine Js

Free Tools

Pixel To Rem Converter Box Shadow Generator

The Larainfo website is dedicated to providing tutorials


on web languages and frameworks such as PHP, Laravel,
API, Livewire, Vue JS, React, and Tailwind CSS..

Quick Link

Home

Laravel

Tailwind CSS

Livewire

[Link] 12/13
4/26/24, 8:16 PM Laravel 9 REST API CRUD Tutorial Example

Quick Link

About us

Disclaimer

Privacy Policy

Terms of use

Contact Us

[Link] 13/13

Common questions

Powered by AI

In Laravel 9, the StorePostRequest class handles authorization logic through the authorize method. By default, this method returns false, which means requests would be unauthorized. Developers must override this method to return true after implementing specific authorization checks relevant to the application. This contract ensures that no sensitive or unwanted operations are performed by unauthorized users, thus safeguarding the integrity of CRUD operations in an API context .

Laravel 9 structures its API controller by adhering to REST principles, organizing actions clearly into methods for handling each type of HTTP request relevant to CRUD. This clear separation of responsibilities within the Api/PostController not only promotes code readability and maintainability but also enforces a consistent API design that aligns with industry standards. Developers can extend and customize these controller methods to handle specific tasks, thus creating more scalable and adaptable APIs that fit varying business logic requirements .

Laravel 9's Model class facilitates database interaction by serving as a powerful Active Record implementation that allows developers to perform CRUD operations without explicitly writing SQL queries. In a typical API CRUD operation, the Model class can be used to instantiate a new resource (like a Post), save it, retrieve data, and update or delete records as necessary. This simplifies data handling and enhances productivity by leveraging Eloquent ORM for fluent and intuitive database management .

The PostResource class in Laravel 9 is used to shape and transform the data that is returned from the API into a more manageable and clean JSON format. It serves as a layer that allows developers to control what information is included in the JSON response to clients, thus ensuring only the necessary and intended data is exposed while maintaining the API's efficiency and security .

In Laravel 9, routing is defined through a straightforward syntax within routes/api.php. The Route::apiResource method is utilized for defining endpoints necessary for CRUD operations linked to a particular API controller, such as Api/PostController. This abstraction simplifies the process of setting up standard routes (index, create, store, show, edit, update, destroy) while automatically tying them to controller actions, streamlining endpoint management in a RESTful context .

Using PHP 8.x is crucial for setting up a Laravel 9 application as it ensures compatibility and supports the latest features offered by the framework. PHP 8.x provides performance improvements, new language features, syntax enhancements, and better error handling, all of which enhance the development experience and application efficiency. Upgrading to PHP 8.x is not just a recommendation but a requirement for leveraging Laravel 9's full potential and achieving optimal security and functionality in modern web applications .

Laravel 9 utilizes the Migration class to manage database schemas through version control, allowing developers to modify and share application databases across different environments. Migrations serve as a blueprint, scripted in PHP, for creating and rolling back database tables without manually running SQL commands. For example, a migration file would define a 'posts' table with fields like 'id', 'title', and 'description', thus ensuring consistent schema structure for all developers involved in a project .

Tailwind CSS enhances Laravel 9 application user interfaces by providing a utility-first CSS framework that simplifies the creation of custom components. Its integration with Laravel supports responsive design and a streamlined styling process, enabling developers to implement complex layouts with less code. Tailwind's flexibility results in cleaner markup and faster styling iterations, significantly improving look and feel without sacrificing performance, particularly valuable in prototyping or frontend-heavy applications .

Laravel 9 uses the Request class to facilitate input validation in its REST API CRUD operations by defining and managing validation rules within custom request classes, like StorePostRequest. These requests ensure data integrity by applying constraints, such as field presence or maximum length, before processing inputs. For instance, StorePostRequest specifies 'title' as a required field with a maximum length of 70 characters and 'description' as required, guaranteeing that only valid data is passed to the database .

To test Laravel 9 REST API CRUD operations using Postman, first ensure your Laravel application is running with the command 'php artisan serve'. Use Postman to issue HTTP requests corresponding to CRUD operations: POST to create entries, GET to retrieve records, PUT/PATCH to update existing entries, and DELETE to remove records. Each request should target the correct endpoint, such as 'http://localhost:8000/api/posts'. Ensure headers are set appropriately, and use a tool like Postman's JSON viewer to interpret responses .

You might also like