Rest APIs are used to create the communication between client and server and in this application we will learn to create rest apis in laravel. Rest API is a architectural style which same as both server and client end so any client can consume the apis since it has industry standard format. Using rest apis we can send request to store client data and can request for any type of data from server.
Rest api is lightweight and most reliable method to connect multiple serve and clients. There can be 5 types of request we can send in rest apis as follow
- GET
- POST
- DELETE
- PUT
So GET
is used to fetch the records and send simple information in query param. POST
mostly used to submit the data and create new records, DELETE
is used to delete records and PUT
is used to update the existing records in application.
In this tutorial we will create all method routes and will implement the basic crud operations. If you want to learn authentication in Rest APIs then you can read How to Implement JWT Auth in Laravel? article.
let’s start the tutorial of Create Rest APIs in Laravel step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project laravel/laravel blog
You can also read this to start with new project
Step 2 : Database Connection
I assume the you have already installed the laravel and basic connection of it like database connection and composer.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-jwt
DB_USERNAME=root
DB_PASSWORD=
Step 3 : Create Model and Migrations
Now, for basic example to retrieve, add , edit and delete i am creating a article model so that we can easily perform basic CRUD operation in rest api
php artisan make:model Article -m
this will generate the model and migration file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
}
and migration file database/migrations/timestamp_create_articles_table.php
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();;
$table->string('title');
$table->string('body')->nullable();
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
and then migrate the migration
php artisan migrate
Step 4 : Create controller
Next, Create a resource controller which by default add the necessary methods for Add, Update, Edit and Delete.
this is not mandatory to create resource controller you can also create custom methods according to your requirements.
php artisan make:controller ArticleController
and add the below code
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
return Article::all();
// return response()->json(["status"=>true, "message"=>"success","data"=>Article::all()]); //or cusom json
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validations=[
'title' => "required",
'email' => "required|email|unique:articles,email",
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
];
$validator = Validator::make($request->all(), $validations);
if ($validator->fails()) {
return response()->json($validator->errors(),422);
}
// save image and name in database
$Article = new Article();
$Article->title = $request->title;
$Article->email = $request->email;
if($request->hasFile("image")){
$file = $request->file("image")->store("uploads/images");
$Article->image = $file;
}
$Article->body = $request->body;
$Article->save();
return response()->json(["status" => true,"data"=>$Article, "message" => "You have successfully created the article."]);
}
public function update(Request $request, $id)
{
$validations=[
'title' => "required",
'email' => "required|email|unique:articles,email,".$id,
];
$validator = Validator::make($request->all(), $validations);
if ($validator->fails()) {
return response()->json($validator->errors(),422);
}
// save image and name in database
$Article = Article::find($id);
$Article->title = $request->title;
$Article->email = $request->email;
if($request->hasFile("image")){
$file = $request->file("image")->store("uploads/images");
$Article->image = $file;
}
$Article->body = $request->body;
$Article->save();
return response()->json(["status" => true,"data"=>$Article, "message" => "You have successfully updated the article."]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Article::find($id)->delete();
return response()->json(["status" => true, "message" => "Record deleted successfully"]);
}
}
Here in above code we have used four methods
Function index : To show all articles.
Function store : To create new article.
Function update : To update the article.
Function destroy : To delete the article.
Note: in a PUT request we can pass additional key _method
=PUT and can send a post request to submit form.
Step 4: Create routes in routes/api.php
Create resource route or route for each api as follow
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
Route::resource('articles', '\App\Http\Controllers\ArticleApiController');
//or
//Route::get('articles', '\App\Http\Controllers\ArticleApiController@index');
//Route::post('articles', '\App\Http\Controllers\ArticleApiController@create');
//Route::delete('articles/{id}', '\App\Http\Controllers\ArticleApiController@destroy');
//Route::put('articles/{id}', '\App\Http\Controllers\ArticleApiController@update');
Screenshot: