Skip to content

Latest commit

 

History

History
3706 lines (2259 loc) · 81.5 KB

laravel.commands.md

File metadata and controls

3706 lines (2259 loc) · 81.5 KB

$$\colorbox{pink}{\large{\color{red}{Laravel \ Framework \ Commands}}}$$

Loading image.....

🔗Home

Topic:

Laravel Installation CMDS

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 CRUD

Laravel 10 Select2 Ajax Autocomplete Search Example

Laravel 10 REST API with Passport Authentication

Top

Laravel Installing CMDS

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

Top

Installing Inertia - React in Laravel Project

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');
});

🔚

Laravel 9 CRUD Example Tutorial for Beginners

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>

Laravel 9 CRUD Example Tutorial

@if ($message = Session::get('success'))

{{ $message }}

@endif @foreach ($companies as $company) @endforeach
S.No Company Name Company Email Company Address Action
{{ $company->id }} {{ $company->name }} {{ $company->email }} {{ $company->address }} Edit @csrf @method('DELETE') Delete
{!! $companies->links() !!}

create.blade.php:

<title>Add Company Form - Laravel 9 CRUD</title>

Add Company

@if(session('status'))
{{ session('status') }}
@endif @csrf
Company Name: @error('name')
{{ $message }}
@enderror
Company Email: @error('email')
{{ $message }}
@enderror
Company Address: @error('address')
{{ $message }}
@enderror
Submit

edit.blade.php:

<title>Edit Company Form - Laravel 9 CRUD Tutorial</title>

Edit Company

@if(session('status'))
{{ session('status') }}
@endif @csrf @method('PUT')
Company Name: @error('name')
{{ $message }}
@enderror
Company Email: @error('email')
{{ $message }}
@enderror
Company Address: @error('address')
{{ $message }}
@enderror
Submit

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')

{{ $message }}
@enderror

Step 7 – Run Development Server

php artisan serve

http://127.0.0.1:8000/companies

🔚

Laravel Breeze Inertia js CRUD with React Tutorial

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 (

Posts / Create

Title setData("title", e.target.value) } /> {errors.title}
Description <textarea type="text" className="w-full rounded" label="description" name="description" errors={errors.description} value={data.description} onChange={(e) => setData("description", e.target.value) } /> {errors.description}
Save
); }; export default Create; app/resources/js/Pages/Post/Index.js import React from "react"; import { Inertia } from "@inertiajs/inertia"; import { InertiaLink, usePage } from "@inertiajs/inertia-react"; const Index = () => { const { posts } = usePage().props; const { data } = posts; return (

Post

Create Post
{data.map(({ id, title, description }) => ( ))} {data.length === 0 && ( )}
# Title Description Action
{id} {title} {description} Edit
No contacts found.
); }; export default Index; app/resources/js/Pages/Post/Edit.js import React from "react"; import { Inertia } from "@inertiajs/inertia"; import { InertiaLink, usePage, useForm } from "@inertiajs/inertia-react"; const Edit = () => { const { post } = usePage().props; const { data, setData, put, errors } = useForm({ title: post.title || "", description: post.description || "", }); function handleSubmit(e) { e.preventDefault(); put(route("posts.update", post.id)); } function destroy() { if (confirm("Are you sure you want to delete this user?")) { Inertia.delete(route("posts.destroy", post.id)); } } return (

Posts / Edit

Title setData("title", e.target.value) } /> {errors.title}
Description <textarea type="text" className="w-full rounded" label="description" name="description" errors={errors.description} value={data.description} onChange={(e) => setData("description", e.target.value) } /> {errors.description}
Update Delete
); }; export default Edit; Laravel Inertia js CRUD with React v3 npm run watch :end: # [Top](#top) Steps for Laravel 9 Vue JS CRUD App using Vite Example: Step 1: Installing fresh new Laravel 9 Application Step 2: Creating Database and Configuration Step 3: Creating Auth with Breeze Step 4: Creating Migration and Model Step 5: Creating Route Step 6: Creating Controller Step 7: Creating Vue Pages Step 8: Testing Step 9: Conclusion Step 1: Installing fresh new Laravel 9 Application composer create-project laravel/laravel vuejs-crud-vite cd vuejs-crud-vite Step 2: Creating Database and Configuration Create Database & Table .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=vuejs-crud-vite DB_USERNAME=root DB_PASSWORD= Step 3: Creating Auth with Breeze composer require laravel/breeze --dev php artisan breeze:install vue npm install npm run dev php artisan migrate Step 4: Creating Migration and Model php artisan make:migration create_posts_table id(); $table->string('title'); $table->text('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }; php artisan migrate php artisan make:model Post Post.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'); require __DIR__.'/auth.php'; Route::resource('posts', PostController::class); Step 6: Creating Controller Create a new file PostController.php in app/Http/Controllers folder $posts]); } /** * Write code on Method * * @return response() */ public function create() { return Inertia::render('Posts/Create'); } /** * Show the form for creating a new resource. * * @return Response */ public function store(Request $request) { Validator::make($request->all(), [ 'title' => ['required'], 'body' => ['required'], ])->validate(); Post::create($request->all()); return redirect()->route('posts.index'); } /** * Write code on Method * * @return response() */ public function edit(Post $post) { return Inertia::render('Posts/Edit', [ 'post' => $post ]); } /** * Show the form for creating a new resource. * * @return Response */ public function update($id, Request $request) { Validator::make($request->all(), [ 'title' => ['required'], 'body' => ['required'], ])->validate(); Post::find($id)->update($request->all()); return redirect()->route('posts.index'); } /** * Show the form for creating a new resource. * * @return Response */ public function destroy($id) { Post::find($id)->delete(); return redirect()->route('posts.index'); } } Step 7: Creating Vue Pages resources/js/Pages Index.vue, Edit.vue & Create.vue resources/js/Pages/Posts/Index.vue <script setup> import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue'; import { Head, Link, useForm } from '@inertiajs/inertia-vue3'; defineProps({ posts: Array, }); const form = useForm(); function destroy(id) { if (confirm("Are you sure you want to Delete")) { form.delete(route('posts.destroy', id)); } } </script>

Laravel 9 Vue JS CRUD App using Vite Example - LaravelTuts.com

Create Post
No. Title Body Action
{{ post.id }} {{ post.title }} {{ post.body }} Edit Delete
resources/js/Pages/Posts/Create.vue <script setup> import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue'; import BreezeLabel from '@/Components/Label.vue'; import BreezeInput from '@/Components/Input.vue'; import BreezeTextArea from '@/Components/Textarea.vue'; import { Head, Link, useForm } from '@inertiajs/inertia-vue3'; const form = useForm({ title: '', body: '' }); const submit = () => { form.post(route('posts.store')); }; </script>

Create Post

Back
{{ form.errors.title }}
{{ form.errors.body }}
Save
resources/js/Pages/Posts/Edit.vue <script setup> import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue'; import BreezeLabel from '@/Components/Label.vue'; import BreezeInput from '@/Components/Input.vue'; import BreezeTextArea from '@/Components/Textarea.vue'; import { Head, Link, useForm } from '@inertiajs/inertia-vue3'; const props = defineProps({ post: Object, }); const form = useForm({ title: props.post.title, body: props.post.body }); const submit = () => { form.put(route('posts.update', props.post.id)); }; </script>

Edit Post

Back
{{ form.errors.title }}
{{ form.errors.body }}
Save
Create a new file Textaarea.vue inside resources/js/Components resources/js/Components/Textarea.vue <script setup> import { onMounted, ref } from 'vue'; defineProps(['modelValue']); defineEmits(['update:modelValue']); const input = ref(null); onMounted(() => { if (input.value.hasAttribute('autofocus')) { input.value.focus(); } }); </script> <textarea class="border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" ref="input"></textarea> Add a Post Navigation in Authenticated.vue inside resources/js/Layouts folder.
Dashboard Posts
Step 8: Testing Now let’s test our Laravel 9 Vue JS CRUD App using Vite Example. Run the following command to start laravel server. php artisan serve npm run dev npm run build http://127.0.0.1:8000/ 🔚 [Top](#top) #Laravel 10 Crud Example Step 1: Install Laravel 10 App Let us begin the tutorial by installing a new laravel 10 application. if you have already created the project, then skip the following step. composer create-project laravel/laravel example-app Step 2: Database Configuration In the second step, we will make a database configuration, we need to add the database name, MySQL username, and password. So let's open the .env file and fill in all details like as below: .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name(blog) DB_USERNAME=here database username(root) DB_PASSWORD=here database password(root) Step 3: Create Migration 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')

Laravel 10 CRUD Example from scratch

@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')

Add New Product

@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')

Edit Product

@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')

Show Product

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>

Laravel 10 Select2 JS Autocomplete Search Example - ItSolutionStuff.com

<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)