🔗Home
Installing Inertia - React in Laravel Project
Laravel 9 CRUD Example Tutorial for Beginners
Laravel Breeze Inertia js CRUD with React Tutorial
Laravel 9 Vue JS CRUD App using Vite Example
Laravel 10 Select2 Ajax Autocomplete Search Example
Laravel 10 REST API with Passport Authentication
Composer create-project command:
composer create-project laravel/laravel example-app
Laravel installer via Composer:
composer global require laravel/installer
laravel new example-app
cd example-app
php artisan serve
composer create-project laravel/laravel <your-project-name>
composer require laravel/jetstream
Install Jetstream With Livewire
php artisan jetstream:install livewire
php artisan jetstream:install livewire --teams
Install Jetstream With Inertia
php artisan jetstream:install inertia
php artisan jetstream:install inertia --teams
Finalizing The Installation:
npm install
npm run dev
php artisan migrate
Livewire:
php artisan vendor:publish --tag=jetstream-views
Laravel Breeze:
composer require laravel/breeze --dev
Breeze & Blade:
php artisan breeze:install
php artisan migrate
npm install
npm run dev
Dark Mode:
php artisan breeze:install --dark
Breeze & React / Vue:
php artisan breeze:install vue
# Or...
php artisan breeze:install react
php artisan migrate
npm install
npm run dev
Server-Side Rendering:
php artisan breeze:install vue --ssr
php artisan breeze:install react --ssr
Breeze & Next.js / API:
php artisan breeze:install api
php artisan migrate
Step 1 - Install the Inertia package in your Laravel project
composer require inertiajs/inertia-laravel
Step 2 - Add root template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale-1.0, maximum-scale=1.0" />
<link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
<script src="{{ mix('/js/app.js') }}" defer></script>
</head>
<body>
@inertia
</body>
</html>
Step 3 - Setup middleware
php artisan inertia:middleware
'web' => [ // ... \App\Http\Middleware\HandleInertiaRequests::class, ],
Step 4 - Install client-side dependencies
npm install @inertiajs/inertia @inertiajs/inertia-react
yarn add @inertiajs/inertia @inertiajs/inertia-react
Step 5 - Initialize app
resources/js/app.js
import React from "react";
import { render } from "react-dom";
import { createinertiaApp } from "@inertiajs/inertia-react";
createInertiaApp({
resolve: name => import(`.Pages/${name}`),
setup({ el, App, props }) {
render(<App {...props} />, el);
}
});
Step 6 - Install babel plugins
npm install @babel/plugin-syntax-dynamic-import
yarn add @babel/plugin-syntax-dynamic-import
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
Step 7 - Create a Test.js component
resources/js/Pages
import React from 'react';
import { Head } from '@inertiajs/inertia-react';
export default function Test() {
return (
<h1>Welcome</h1>
)
}
Step 8 - Make controller and route
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Inertia\Inertia;
class TestController extends Controller
{
public function show() {
return Inertia::render('Test');
}
}
Route::group([
"middleware" => ["auth"],
], function(){
Route::get('/test', 'TestController@show');
});
🔚
Use the following steps to create a crud operation app in laravel 9 as follows:
Step 1 – Download Laravel 9 App
Step 2 – Setup Database with App
Step 3 – Create Company Model & Migration For CRUD App
Step 4 – Create Company Controller By Artisan Command
Step 5 – Create Routes
Step 6 – Create Blade Views File
Make Directory Name Companies
index.blade.php
create.blade.php
edit.blade.php
Step 7 – Run Laravel CRUD App on Development Server
composer create-project --prefer-dist laravel/laravel:^9.0 laravel-9-crud
Step 2 – Setup Database with App
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password
Step 3 – Create Company Model & Migration For CRUD App
php artisan make:model Company -m
public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('address'); $table->timestamps(); }); }
app/Models/Company.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'address'];
}
php artisan migrate
Step 4 – Create Company Controller By Artisan Command
php artisan make:controller CompanyController
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;
class CompanyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$companies = Company::orderBy('id','desc')->paginate(5);
return view('companies.index', compact('companies'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('companies.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'address' => 'required',
]);
Company::create($request->post());
return redirect()->route('companies.index')->with('success','Company has been created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\company $company
* @return \Illuminate\Http\Response
*/
public function show(Company $company)
{
return view('companies.show',compact('company'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Company $company
* @return \Illuminate\Http\Response
*/
public function edit(Company $company)
{
return view('companies.edit',compact('company'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\company $company
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Company $company)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'address' => 'required',
]);
$company->fill($request->post())->save();
return redirect()->route('companies.index')->with('success','Company Has Been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Company $company
* @return \Illuminate\Http\Response
*/
public function destroy(Company $company)
{
$company->delete();
return redirect()->route('companies.index')->with('success','Company has been deleted successfully');
}
}
Step 5 – Create Routes
use App\Http\Controllers\CompanyController;
Route::resource('companies', CompanyController::class);
Step 6 – Create Blade Views File
Make Directory Name Companies
index.blade.php
create.blade.php
edit.blade.php
index.blade.php:
<title>Laravel 9 CRUD Tutorial Example</title>{{ $message }}
S.No | Company Name | Company Email | Company Address | Action |
---|---|---|---|---|
{{ $company->id }} | {{ $company->name }} | {{ $company->email }} | {{ $company->address }} | Edit @csrf @method('DELETE') Delete |
create.blade.php:
<title>Add Company Form - Laravel 9 CRUD</title>edit.blade.php:
<title>Edit Company Form - Laravel 9 CRUD Tutorial</title>If you submit the add or edit form blank. So the error message will be displayed with the help of the code given below:
@error('name')
Step 7 – Run Development Server
php artisan serve
http://127.0.0.1:8000/companies
🔚
Step 1: Install Laravel & Connect Database
Step 2: Install Breeze & Setup Inertia Js React
Step 3: Create Post Model and Resource Controller
Step 4: Create Post Request
Step 5: Create React js view file for CRUD
Step 1: Install Laravel & Connect Database
composer create-project laravel/laravel inertia-react
.env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database_name DB_USERNAME=database_user_name DB_PASSWORD=database_password
Step 2: Install Breeze & Setup Inertia Js React
composer require laravel/breeze --dev
php artisan breeze:install
php artisan breeze:install react
npm install && npm run dev
Step 3: Create Post Model and Resource Controller
php artisan make:model Post -mcr
app/database/migrations/posts_table.php
id(); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } } app/Models/Post.php 'required', 'description' => 'required' ]; } } PostController.php get(); return Inertia::render('Post/Index', ['posts' => $posts]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return Inertia::render('Post/Create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StorePostRequest $request) { Post::create( $request->validated() ); return Redirect::route('posts.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Post $post) { return Inertia::render('Post/Edit', [ 'post' => [ 'id' => $post->id, 'title' => $post->title, 'description' => $post->description ] ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(StorePostRequest $request, Post $post) { $post->update($request->validated()); return Redirect::route('posts.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Post $post) { $post->delete(); return Redirect::route('posts.index'); } } app/routes/web.php Route::has('login'), 'canRegister' => Route::has('register'), 'laravelVersion' => Application::VERSION, 'phpVersion' => PHP_VERSION, ]); }); Route::get('/dashboard', function () { return Inertia::render('Dashboard'); })->middleware(['auth', 'verified'])->name('dashboard'); Route::resource('posts', PostController::class); require __DIR__.'/auth.php'; Step 5: Create React js view file for CRUD app/resources/js/Pages/Post/Create.js import React from "react"; import { Inertia } from "@inertiajs/inertia"; import { InertiaLink, useForm } from "@inertiajs/inertia-react"; const Create = () => { const { data, setData, errors, post } = useForm({ title: "", description: "", }); function handleSubmit(e) { e.preventDefault(); post(route("posts.store")); } return (No. | Title | Body | Action |
---|---|---|---|
{{ post.id }} | {{ post.title }} | {{ post.body }} | Edit Delete |
id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
};
Now you have to run this migration by the following command:
php artisan migrate
php artisan make:migration create_products_table --create=products
After this command you will find one file in the following path "database/migrations" and you have to put below code in your migration file for creating the products table.
Now you have to run this migration by the following command:
php artisan migrate
Step 4: Create Controller and Model
In this step, now we should create new resource controller as ProductController. So run bellow command and create new controller. bellow controller for create resource controller.
php artisan make:controller ProductController --resource --model=Product
In this controller will create seven methods by default as bellow methods:
1)index()
2)create()
3)store()
4)show()
5)edit()
6)update()
7)destroy()
So, let's copy bellow code and put on ProductController.php file.
app/Http/Controllers/ProductController.php
paginate(5);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*/
public function create(): View
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*/
public function show(Product $product): View
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Product $product): View
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Product $product): RedirectResponse
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
$product->update($request->all());
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Product $product): RedirectResponse
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
}
Step 5: Add Resource Route
Here, we need to add resource route for product crud application. so open your "routes/web.php" file and add following route.
routes/web.php
Step 6: Add Blade Files
In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "products" then create blade files of crud app. So finally you have to create following bellow blade file:
1) layout.blade.php
2) index.blade.php
3) create.blade.php
4) edit.blade.php
5) show.blade.php
So let's just create following file and put bellow code.
resources/views/products/layout.blade.php
<title>Laravel 10 CRUD Application - ItSolutionStuff.com</title>
@yield('content')
resources/views/products/index.blade.php
@extends('products.layout')
@section('content')
@if ($message = Session::get('success'))
{{ $message }}
@endif
@foreach ($products as $product)
@endforeach
No
Name
Details
Action
{{ ++$i }}
{{ $product->name }}
{{ $product->detail }}
Show
Edit
@csrf
@method('DELETE')
Delete
{!! $products->links() !!}
@endsection
resources/views/products/create.blade.php
@extends('products.layout')
@section('content')
@if ($errors->any())
Whoops! There were some problems with your input.
@foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif
@csrf
Name:
Detail:
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
Submit
@endsection
resources/views/products/edit.blade.php
@extends('products.layout')
@section('content')
@if ($errors->any())
Whoops! There were some problems with your input.
@foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif
@csrf
@method('PUT')
Name:
Detail:
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
Submit
@endsection
resources/views/products/show.blade.php
@extends('products.layout')
@section('content')
Name:
{{ $product->name }}
Details:
{{ $product->detail }}
@endsection
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
Read Also: Laravel 10 REST API with Passport Authentication Tutorial
http://localhost:8000/products
:end:
#
[Top](#top)
#Laravel 10 Select2 Ajax Autocomplete Search Example
Step 1: Install Laravel 10
composer create-project laravel/laravel example-app
Step 2: Add Dummy Users
First, we need to run default migrations, so we have created new users table. so let's run migration command:
php artisan migrate
next, we will create some dummy users using tinker factory. so let's create dummy records using bellow command:
php artisan tinker
User::factory()->count(20)->create()
Step 3: Create Controller
app/Http/Controllers/SearchController.php
filled('q')){
$data = User::select("name", "id")
->where('name', 'LIKE', '%'. $request->get('q'). '%')
->get();
}
return response()->json($data);
}
}
Step 4: Create Routes
routes/web.php
group(function(){
Route::get('demo-search', 'index');
Route::get('autocomplete', 'autocomplete')->name('autocomplete');
});
Step 5: Create View File
resources/views/searchDemo.blade.php
<title>Laravel 10 Select2 JS Autocomplete Search Example - ItSolutionStuff.com</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('#search').select2({
placeholder: 'Select an user',
ajax: {
url: path,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});
</script>
php artisan serve
http://localhost:8000/demo-search
:end:
#
#Laravel 10 REST API with Passport Authentication Tutorial
Step 1: Install Laravel 10
composer create-project laravel/laravel example-app
Step 2: Install Passport
composer require laravel/passport
php artisan migrate
php artisan passport:install
Step 3: Passport Configuration
app/Models/User.php
'datetime',
];
}
config/auth.php
[
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
.....
]
Step 4: Add Product Table and Model
php artisan make:migration create_products_table
id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
php artisan migrate
app/Models/Product.php
Step 5: Create API Routes
routes/api.php
group( function () {
Route::resource('products', ProductController::class);
});
Step 6: Create Controller Files
app/Http/Controllers/API/BaseController.php
true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
app/Http/Controllers/API/RegisterController.php
all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User register successfully.');
}
/**
* Login api
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request): JsonResponse
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
app/Http/Controllers/API/ProductController.php
sendResponse(ProductResource::collection($products), 'Products retrieved successfully.');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request): JsonResponse
{
$input = $request->all();
$validator = Validator::make($input, [
'name' => 'required',
'detail' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$product = Product::create($input);
return $this->sendResponse(new ProductResource($product), 'Product created successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id): JsonResponse
{
$product = Product::find($id);
if (is_null($product)) {
return $this->sendError('Product not found.');
}
return $this->sendResponse(new ProductResource($product), 'Product retrieved successfully.');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product): JsonResponse
{
$input = $request->all();
$validator = Validator::make($input, [
'name' => 'required',
'detail' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$product->name = $input['name'];
$product->detail = $input['detail'];
$product->save();
return $this->sendResponse(new ProductResource($product), 'Product updated successfully.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product): JsonResponse
{
$product->delete();
return $this->sendResponse([], 'Product deleted successfully.');
}
}
php artisan make:resource ProductResource
$this->id,
'name' => $this->name,
'detail' => $this->detail,
'created_at' => $this->created_at->format('d/m/Y'),
'updated_at' => $this->updated_at->format('d/m/Y'),
];
}
}
php artisan serve
make sure in details api we will use following headers as listed bellow:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
Testing Apis in PostMan:
Now simply you can run above listed url like as bellow screen shot:
1) Register API: Verb:GET, URL:http://localhost:8000/api/register
2) Login API: Verb:GET, URL:http://localhost:8000/api/login
3) Product List API: Verb:GET, URL:http://localhost:8000/api/products
4) Product Create API: Verb:POST, URL:http://localhost:8000/api/products
5) Product Show API: Verb:GET, URL:http://localhost:8000/api/products/{id}
6) Product Update API: Verb:PUT, URL:http://localhost:8000/api/products/{id}
7) Product Delete API: Verb:DELETE, URL:http://localhost:8000/api/products/{id}
#
[Top](#top)