Laravel 8 Full Text Search with Ajax Example

Laravel 8 Full Text Search with Ajax Example

Hi Men,

In this blog,I'm able to examine you how to use complete text search using ajax in laravel.you could easy and surely use complete textual content search using ajax in laravel.

This is one greater put up on Laravel 8 and on this post you may discover a way to put into effect complete text search in Laravel eight framework through the use of Ajax with Searchable Laravel package. if you desired to discover ways to make full text seek in you Laravel 8 software? If sure, then this put up will help you may gaining knowledge of this subject matter.

Here in this submit we've got percentage academic on a way to create complete textual content search with the aid of using "nicolaslopezj/searchable" package with Ajax in Laravel eight framework. So, consumer can get searchable facts on internet page without refresh of net page, due to the fact here we have use Ajax in Laravel eight framework.

You need to realize what's complete textual content search. So, complete textual content seek is a one type of seek method, which seek data on each word of request to your database. most of engines like google has been used complete text search technique for search records on each word of seek request and seek result on internet web page. it is more advance level for search a information in database.

Download Laravel 8 framework

For make any Laravel 8 application, first we need to download and install Laravel 8 framework. So, in this step of Laravel 8 tutorial, we have to go command prompt and go directory in which we want to download load and install Laravel 8 framework. We have to write and run following command.

composer create-project --prefer-dist laravel/laravel laravel-8	
Download and Install Searchable Package

In this Laravel 8 tutorial, We need to make Full text search feature in Laravel 8 application. For this here we have use "nicolaslopezj/searchable" package. For this we have to go command prompt and run following command. This command will download and install this searchable package in Laravel 8 application.

composer require nicolaslopezj/searchable
Make Database Connection

Before making Mysql Database connection, first we need to create table in your database. For this, you have to run following SQL script.

CREATE TABLE `full_text_searches` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) NOT NULL,
  `Gender` varchar(30) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `full_text_searches`
--

INSERT INTO `full_text_searches` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom'),
(144, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(143, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(141, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(142, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(140, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States'),
(139, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(138, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(136, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(137, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(145, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States');

Now we want to make database connection in Laravel 6 framework. For this we have to open .env and in this file we have to define Mysql Database configuration.

.env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=
Create Model

Here we have use Model class for builder database query, so for this we have to create model class, so we have go to command prompt and write following command.

php artisan make:model Full_text_search --migration
app/Models/Full_text_search.php
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;

class Full_text_search extends Model
{
    use Notifiable;
    use SearchableTrait;

    /**
     * Write code on searchable
     *
     * 
     */
    protected $searchable = [
        'columns' => [
            'full_text_searches.CustomerName'  => 10,
            'full_text_searches.Gender'   => 10,
            'full_text_searches.Address'   => 10,
            'full_text_searches.City'    => 10,
            'full_text_searches.PostalCode'  => 10,
            'full_text_searches.Country'   => 10,
            'full_text_searches.id'    => 10,
        ]
    ];

    /**
     * Write code on fillable
     *
     * 
     */
    protected $fillable = [
        'CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country',
    ];
}
Set Controller Method Route

In Laravel 8 application, we need to set the route of all controller method, for this we have to open routes/web.php file and in this file we have define route which you can find below.

routes/web.php
<?php
<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Full_text_search_Controller;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('full-text-search', [Full_text_search_Controller::class,'index']);
Route::post('full-text-search/action', [Full_text_search_Controller::class,'action'])->name('full-text-search.action');
?>
Create Controller

For handle HTTP request we need to create controller in Laravel 6 application. For create controller here we have use compser command for this we have go to command prompt and run following command.

php artisan make:controller Full_text_search_Controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FullTextSearch;
use DataTables;

class FullTextSearchController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('fullText.fullTextSearch');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function action(Request $request)
    {
      if($request->ajax())
      {
        $data = FullTextSearch::search($request->get('full_text_search_query'))->get();
        return response()->json($data);
      }
    }
}
Create View Blade File

For display output in browser, we need to create blade file in resources/views folder. Here we have create full_text_search.blade.php file in this folder. In this file first we have to create on search box for search data and then after we have create one table. After this we have to write Ajax request, which will send ajax request to action() method of controller and it will received full text search data in json format and convert into HTML table and display on web page using jQuery. This Ajax request will be trigger when we have click on search button. Whole source code of this file you can get below.

resources/views/full_text_search.blade.php
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Full Text Search in Laravel using Ajax Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Full Text Search in Laravel using Ajax Example</h3>
     <br />
     <div class="row">
      <div class="col-md-6">
       <input type="text" name="full_text_search" id="full_text_search" class="form-control" placeholder="Search" value="">
      </div>
      <div class="col-md-2">
       @csrf
       <button type="button" name="search" id="search" class="btn btn-success">Search</button>
      </div>
     </div>
     <br />
     <div class="table-responsive">
    <table class="table table-bordered table-hover">
        <thead>
         <tr>
            <th>Customer Name</th>
            <th>Gender</th>
            <th>Address</th>
                  <th>City</th>
                  <th>Postal Code</th>
                  <th>Country</th>
         </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
        </div>
 </body>
</html>


<script>
$(document).ready(function(){

 load_data('');

 function load_data(full_text_search_query = '')
 {
  var _token = $("input[name=_token]").val();
  $.ajax({
   url:"{{ route('full-text-search.action') }}",
   method:"POST",
   data:{full_text_search_query:full_text_search_query, _token:_token},
   dataType:"json",
   success:function(data)
   {
    var output = '';
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<tr>';
      output += '<td>'+data[count].CustomerName+'</td>';
      output += '<td>'+data[count].Gender+'</td>';
      output += '<td>'+data[count].Address+'</td>';
      output += '<td>'+data[count].City+'</td>';
      output += '<td>'+data[count].PostalCode+'</td>';
      output += '<td>'+data[count].Country+'</td>';
      output += '</tr>';
     }
    }
    else
    {
     output += '<tr>';
     output += '<td colspan="6">No Data Found</td>';
     output += '</tr>';
    }
    $('tbody').html(output);
   }
  });
 }

 $('#search').click(function(){
  var full_text_search_query = $('#full_text_search').val();
  load_data(full_text_search_query);
 });

});
</script>
Run Laravel 8 Application

After all code is ready, lastly we need to start Laravel 6 framework server. For this we have to go command prompt and write following command.

php artisan serve

This command will start server and give you base url of your application. For test above code you have write following url in your browser.

localhost:8000/full-text-search

It will help you...

Laravel 8 Ajax Pagination Example

Laravel 8 Ajax Pagination Example

Hi Men,

In this blog, I can provide an explanation for you the way to create jquery ajax pagination in laravel eight, we will create ajax pagination in laravel 8. i will show a little by little easy ajax pagination in laravel 8.

A pagination helps us to load few records every time, that way cannot broken net web page due to masses of information. in case you are making pagination and do it the use of ajax then it a better way. Ajax Pagination load most effective your table facts rather than the entire page. So ajax pagination is very useful.

We simply create "product" table the use of migration command and add a few dummy records. After that, we are able to create one direction for display view and write code jquery ajax on blade report. So, you need to simply follow beneath step and you will get virtually ajax pagination in laravel 8

Right here, I give you full example of ajax pagination instance grade by grade like create laravel eight undertaking, migration, model, direction, blade file and so forth. so that you have to just observe few steps.

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create products Table and Model

In this step we have to create migration for products table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Product -m

After this command you have to put bellow code in your migration file for create products table.

following path: /database/migrations/2020_01_10_102325_create_products_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create products table.

following path:/app/Models/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{	
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = [
        'name',
    ];
}
Step 3: Create Route

In this is step we need to create route for ajax pagination layout file

following path:/routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\AjaxPaginationController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('pagination-ajax','AjaxPaginationController@ajaxPagination')->name('ajax.pagination');
Step 4: Create Controller

here this step now we should create new controller as AjaxPaginationController,So run bellow command for generate new controller

php artisan make:controller AjaxPaginationController

now this step, this controller will manage ajax pagination layout bellow content in controller file.following fille path

following path:/app/Http/Controllers/AjaxPaginationController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class AjaxPaginationController extends Controller
{
  /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
  public function ajaxPagination(Request $request)
  {
    $products = Product::paginate(5);
  
    if ($request->ajax()) {
        return view('presult', compact('products'));
    }
  
    return view('ajaxPagination',compact('products'));
  }
}
Step 5: Create Blade Files

In Last step, let's create ajaxPagination.blade.php (resources/views/ajaxPagination.blade.php) for layout and lists all product code here and put following code

following path:/resources/views/ajaxPagination.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax Pagination Example </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
  
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <div class="card-header">
                    <h5>Laravel 8 Ajax Pagination Example </h5>
                </div>
                <div class="card-body" id="tag_container">
                   @include('presult')
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            }else{
                getData(page);
            }
        }
    });
    
    $(document).ready(function()
    {
        $(document).on('click', '.pagination a',function(event)
        {
            event.preventDefault();
  
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
  
            var myurl = $(this).attr('href');
            var page=$(this).attr('href').split('page=')[1];
  
            getData(page);
        });
  
    });
  
    function getData(page){
        $.ajax(
        {
            url: '?page=' + page,
            type: "get",
            datatype: "html"
        }).done(function(data){
            $("#tag_container").empty().html(data);
            location.hash = page;
        }).fail(function(jqXHR, ajaxOptions, thrownError){
              alert('No response from server');
        });
    }
</script>
  
</body>
</html>
resources/views/presult.blade.php
<table class="table table-bordered">
    <thead>
        <tr>
            <th width="100px">Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($products as $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
{!! $products->render() !!}

Now you have some dummy data on your products table before run this example. Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/pagination-ajax

It will help you...

Laravel Ajax Image Upload Example

Laravel Ajax Image Upload Example

Hi Dev,

Nowadays, i'm able to give an explanation for the way to you can jquery ajax photograph add laravel.we're display laravel image upload the usage of ajax. you can clean image upload using ajax in laravel. i will inform jquery ajax picture add laravel.i'm able to display full example of laravel ajax image upload.

We will learn how to upload picture the usage of jquery ajax. In this situation i take advantage of FormJS for fireplace Ajax that manner we can definitely use laravel validation and additionally print laravel blunders message.

Here, I give you complete example of ajax photo importing grade by grade like create laravel challenge, migration, model, path, blade file and many others. so that you ought to just follow few steps.

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 3: Create ajax_images Table and Model

In this step we have to create migration for images table using Laravel php artisan command, so first fire bellow command:

php artisan make:model Image -m

After this command you have to put bellow code in your migration file for create Image table.

following path:/database/migrations/2020_01_10_102325_create_images_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('image');
            $table->timestamps();
        });
    }

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Image table.

following path:/app/Models/Image.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = ['title','image'];
}
Step 4: Create Route

In this is step we need to create route for ajax image upload layout file and another one for post request.open following fille path

following path:/routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadAjaxController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('imageUploadAjax', 'ImageUploadAjaxController@imageUploadAjax');
Route::post('imageUploadAjax', 'ImageUploadAjaxController@imageUploadAjaxPost')->name('imageUploadsAjax');
Step 5: Create Controller

Here this step now we should create new controller as ImageUploadAjaxController,So run bellow command for generate new controller

php artisan make:controller ImageUploadAjaxController

now this step, this controller will manage layout and image validation with post request,bellow content in controller file.following fille path

following path:/app/Http/Controllers/ImageUploadAjaxController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Models\Image;

class ImageUploadAjaxController extends Controller
{
     /**
     * Show the application ajaxImageUpload.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadAjax()
    {
      return view('imageUploadAjax');
    }
    
    /**
     * Show the application ajaxImageUploadPost.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadAjaxPost(Request $request)
    {
      $validator = Validator::make($request->all(), [
        'title' => 'required',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      ]);

      if ($validator->passes()) {

        $inputData['title'] = $request->title;
        $inputData['image'] = time().'.'.$request->image->extension();
        $request->image->move(public_path('images'), $inputData['image']);

        Image::create($inputData);
        
        return response()->json(['success'=>'done']);
      }
      
      return response()->json(['error'=>$validator->errors()->all()]);
    }
}
Step 6: Create View

In Last step, let's create ajaxImageUpload.blade.php(resources/views/imageUploadAjax.blade.php) for layout and we will write design code here and also form for ajax image upload, So put following code:

following path:resources/views/imageUploadAjax.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>Laravel - Ajax Image Uploading Tutorial</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<div class="container">
  <div class="col-md-8 col-md-offset-2">
    <h3>Laravel - Ajax Image Uploading Tutorial</h3>
    <form action="{{ route('imageUploadsAjax') }}" enctype="multipart/form-data" method="POST">
      <div class="alert alert-danger print-error-msg" style="display:none">
          <ul></ul>
      </div>
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      <div class="form-group">
        <label>Title:</label>
        <input type="text" name="title" class="form-control" placeholder="Add Title">
      </div>
      <div class="form-group">
        <label>Image:</label>
        <input type="file" name="image" class="form-control">
      </div>
      <div class="form-group">
        <button class="btn btn-success upload-image" type="submit">Upload Image</button>
      </div>
    </form>
  </div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/formjs/1.1.1/formjs.min.css"></script>
<script type="text/javascript">
  $("body").on("click",".upload-image",function(e){
    $(this).parents("form").ajaxForm(options);
  });
  var options = { 
    complete: function(response) 
    {
      if($.isEmptyObject(response.responseJSON.error)){
        $("input[name='title']").val('');
        alert('Image Upload Successfully.');
      }else{
        printErrorMsg(response.responseJSON.error);
      }
    }
  };
  function printErrorMsg (msg) {
  $(".print-error-msg").find("ul").html('');
  $(".print-error-msg").css('display','block');
  $.each( msg, function( key, value ) {
    $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
  });
  }
</script>
</body>
</html>
Create folder images Create you have to create "images" folder in your public directory. following path:/public/images

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/imageUploadAjax

It will help you...

Laravel str afterLast() function Example

Laravel str afterLast() function

Hi Guys,

Today,I will learn you how to use laravel str afterLast() function example. We will show example of afterLast function in laravel.The Str::afterLast method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string.

Here, I will give you full example for simply str afterLast() method in laravel as bellow.

Example
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\FileController;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
        \Log::info($slice);
        //'Controller'
    }
}
Output
'Controller'

It Will help you...

Laravel 8 Spatie Medialibrary Example

Laravel Spatie Medialibrary

Hi Guys,

Nowadays, I can study you the way to use spatie medialibrary in laravel 8 application,we are able to show example of laravel spatie medialibrary.you can easliy use spatie media library laravel eight.this package use to add a image or an avatar. in this academic we will show you an smooth manner to feature it, using Spatie’s Media Library bundle.

In this post, let’s move over the well-known laravel medialibrary package deal evolved by way of Spatie. This bundle deal can accomplice all sorts of documents together with your Eloquent models.

Here, I'm able to give you full example for spatie media library laravel eight as bellow.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel post
Step 2 : Database Configuration

>In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(post)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install Spatie Medialibrary

In this step, we need laravel/Spatie Medialibrary package. you can install Spatie Medialibrary package using bellow command so let's run bellow command

composer require "spatie/laravel-medialibrary:^9.6.0"

After the package is installed, run the following command to copy the migration file from to package directory to your project directory and also to run the fresh migration command.

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"

php artisan migrate
Step 4: Create Model and Migration

here this step, we will create one model and migration name post. Use the below following command and create it

php artisan make:model post -m

Next,Open post migration file and put the below code. here following path of migration file

Path: /database/migrations/2020_05_27_095534_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

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

Next, go to app/post.php and open post model file and put the below code. here following path of model fille

Path:/app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Post extends Model implements HasMedia
{
    use HasFactory,InteractsWithMedia;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'body',
    ];
}
Step 5: Create Route

Create two routes one for show form and the second route send data to the server:

here following path of route fille

Path:/routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('post',[PostController::class,'index'])->name('post');
Route::get('post/create',[PostController::class,'create'])->name('post.create');
Route::post('post/store',[PostController::class,'store'])->name('post.store');
Step 6:Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller PostController 

Here this step,we will create two methods inside the controller first index method is used to display post form and second store method is used to store data in the mysql database and image upload Medialibrary to storge folder

here following path of Controller fille.

Path:/app/Http/Controllers/postController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        $posts = Post::latest()->get();

        return view('post.index',compact('posts'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $post = Post::create($input);

        if($request->hasFile('image') && $request->file('image')->isValid()){
            $post->addMediaFromRequest('image')->toMediaCollection('images');
        }

        return redirect()->route('post');
    }
}
Step 7:Create a blade view

In this step, we will create two blade file name post/index.blade.php and post/create.blade.php.

here following path of index.blade fille

Path:/resources/views/post/index.blade.php

<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel 8 Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('post.create') }}" class="btn btn-success btn-sm">Create</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Title</th>
                                <th width="25%">Image</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($posts as $key=>$post)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $post->title }}</td>
                                    <td><img src="{{$post->getFirstMediaUrl('images', 'thumb')}}" / width="100%"></td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Next following path create a create.blade fille

Path:/resources/views/post/create.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel 8 Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('post') }}" class="btn btn-info btn-sm">Back</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <div class="form-group">
                                    <label for="">Title:</label>
                                    <input type="" name="title" class="form-control" placeholder="Enter Title">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Body:</label>
                                <textarea name="body" id="" class="form-control" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Image:</label>
                                <input type="file" name="image" class="form-control">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3 text-center">
                                <button class="btn btn-success btn-block">Submit</button>
                            </div>
                        </div>    
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

After Note that to view the files in the browser you need to make the files public that is stored in the storage directory, you need to run the following command on your project root in terminal/command-line.

php artisan storage:link
next change .env file in APP_URL path
......
APP_URL=http://localhost:9000
......

Now, we will use the php artisan serve command.

php artisan serve --port=9000

Now we are ready to run our example so run bellow command to quick run.

http://localhost:9000/post

It will help you...

Laravel Select2 Ajax Autocomplete Example

Hi Dev,

Nowadays, I will create auto whole the use of Select2 and Ajax in laravel. we are able to show automobile whole the use of select2.js in laravel. you can easyli create auto whole the usage of select2 and ajax in laravel.

I will give you full example of select2 ajax in laravel.

Step 1 : Install Laravel 7 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

.env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create product Table and Model

In this step we have to create migration for product table using Laravel 6 php artisan command, so first fire bellow command:

php artisan make:model Product -m

After this command you have to put bellow code in your migration file for create product table.

/database/migrations/2020_03_05_100722_create_product_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
Now we require to run migration be bellow command:
php artisan migrate
After you have to put bellow code in your model file for create product table. /app/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected $fillable = [
        'name', 'price',
    ];
}
Step 3: Create Route

now, we need to add resource route for select2 crud operations in laravel application. so open your "routes/web.php" file and add following route.

/routes/web.php
Route::get('select2', 'Select2AutocompleteController@index');
Route::get('/select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');
Step 4: Create Controller

here this step now we should create new controller as Select2AutocompleteController. So run bellow command and create new controller.

php artisan make:controller Select2AutocompleteController

In this controller will create two methods by default as bellow methods:

1)index()

2)dataAjax()

So, let's copy bellow code and put on ItemController.php file.

/app/Http/Controllers/Select2AutocompleteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;

class Select2AutocompleteController extends Controller
{
    /**
    * Show the application layout.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
    	return view('select2.index');
    }
    
    /**
    * Show the application dataAjax.
    *
    * @return \Illuminate\Http\Response
    */
    public function dataAjax(Request $request)
    {
    	$data = [];

        if($request->has('q')){
            $search = $request->q;
            $data =Product::select("id","name")
            		->where('name','LIKE',"%$search%")
            		->get();
        }
        return response()->json($data);
    }
}
Step 5:Create View

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 "select2" then create blade files of crud app. So finally you have to create following bellow blade file:

here create following file and put bellow code.

/resources/views/select2/index.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>Laravel - Dynamic autocomplete search using select2 JS Ajax</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body class="bg-dark">
<div class="container mt-4">
  <div class="row">
    <div class="col-md-8 offset-md-2">
      <div class="card">
        <div class="card-header">
          <h4>Laravel - Dynamic autocomplete search using select2 JS Ajax</h4>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-12">
              <select class="itemName form-control" name="itemName"></select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script type="text/javascript">
$('.itemName').select2({
  placeholder: 'Select an item',
  ajax: {
    url: '/select2-autocomplete-ajax',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>
</html>
Now we are ready to run our example so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/select2

It will help you...

Laravel 8 Socialite Login with Google Gmail Account

Laravel 8 Socialite Login with Google Gmail Account

Hello Dev,

Today, I can provide an explanation for you grade by grade login with google account in laravel 8 using socialite. laravel 8 socialite offer api to login with gmail account. you could without difficulty login the usage of google account in laravel 8 utility.

As we understand social media is a end up more and more famous within the global. each one have social account like gmail, facebook and so forth. i think additionally maximum of have gmail account. So if to your application have login with social then it come to be first-rate. you bought more people hook up with your internet site because maximum of people does no longer want to fill join up or register shape. If there login with social than it turn out to be remarkable.

So if you want to also implement login with google gmail account then i will help you step by step instruction. let's follow tutorial and implement it.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.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 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4 : Install Socialite

In this step, we need laravel/socialite package. you can install socialite package using bellow command so let's run bellow command :

composer require laravel/socialite

After install above package you can add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

config/app.php
....

'providers' => [
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

....
Step 5: Create Google App

Here we need google client id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : Google Developers Console. you can find bellow screen :

Laravel 8 Socialite Login with Google Gmail Account

Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:

Laravel 8 Socialite Login with Google Gmail Account
Laravel 8 Socialite Login with Google Gmail Account

after create account you can copy client id and secret.

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.
return [
    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]
Step 6: Add Database Column

In this step first we have to create migration for add google_id in your user table. So let's run bellow command:

php artisan make:migration add_google_id_column_in_users_table  --table=users
database/migrations/2020_09_18_052105_add_google_id_column_in_users_table.php
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGoogleIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('google_id');
         });
    }
}

Update mode like this way:

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 7: Create Routes

Here, we need to add resource route for login with gmail account. so open your "routes/web.php" file and add following route.

routes/web.php
use App\Http\Controllers\Auth\GoogleController;

Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Step 8: Create Controller

After add route, we need to add method of google auth that method will handle google callback url and etc, first put bellow code on your GoogleController.php file

app/Http/Controllers/Auth/GoogleController.php
<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGoogleCallback()
    {
        try {
    
            $user = Socialite::driver('google')->user();
     
            $finduser = User::where('google_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/dashboard');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/dashboard');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 9: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                    <a href="{{ url('auth/google') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2 btn-google">
                      <strong>Login With Google</strong>
                    </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Now we are ready to run laravel 8 socialite login with Google gmail account so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/login
Output
Laravel 8 Socialite Login with Google Gmail Account

It will help you...

Laravel Scout Algolia Full Text Search Example

Hi Guys

Today,I will tell how you can full text search utilizing scout algolia. i will show the example of laravel scout algolia full text search.you can full text search utilizing scout algolia api.it can this example full expound scout algolia full text search.

I will show the rudimental step of scout algolia api full text search.if you can utilize full text search for install scout and Algolia api package.we are utilizing algolia api utilizing full text search example in laravel.

Here the following steps example laravel full text search Using scout algolia

Step 1: Create Laravel Project

In this step create laravel project following command.

composer create-project --prefer-dist laravel/blog
Step 2: Database Configuration

After create laravel project , we require to make database configuration, you have to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 3: Install Scout Package

In this step you are install scout package blow the command.

composer require laravel/scout

After installing Scout, you should publish the Scout configuration using the vendor: publish Artisan command.

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application’s web interface.

Set the value of queue in the .env file.

following path: .env
SCOUT_QUEUE = true
Step 4: Install Algolia Driver.

you will also want to install the algolia php sdk via the composer package manager,

composer require algolia/algoliasearch-client-php

Next, we have to set id and secret of Algolia. So move to this website Algolia and then create your account.

After login, You can get id and secret from this link: https://www.algolia.com/api-keys

Laravel Scout Algolia Full Text Search Example

You can set id and secret in your .env file.

Set the value of queue in the .env file.

following path: .env
ALGOLIA_APP_ID = Enter your Application ID
ALGOLIA_SECRET = Enter your Admin API Key
Step 5: Create Posts Table and Model

In this step we have to create migration for posts table using Laravel project php artisan command, so first fire bellow command:

php artisan make:model Post -m

After this command you have to put bellow code in your migration file for create posts table.

following path:/database/migrations/2020_01_10_102325_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->string('category');
            $table->integer('view');
            $table->timestamps();
        });
    }

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Post table.

following path:/app/Post.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
	use Searchable;

    protected $fillable = ['title','body','category','view'];
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function searchableAs()
    {
        return 'post_index';
    }
}
Step:6 Batch Import

In this step insert some records database records need to import into your search driver. scout provides an artisan command that you may use to import all of your existing records into your search indexes.

php artisan scout:import "App\Post"
Step 7: Create Route

In this is step we need to create route for post search layout file

following path:/routes/web.php
Route::get('index','SearchController@search');
Step 8: Create Controller

here this step now we should create new controller as SearchController,So run bellow command for generate new controller

php artisan make:controller SearchController

now this step, this controller will manage layout post search request,bellow content in controller file.following fille path

following path:/app/Http/Controllers/SearchController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class SearchController extends Controller
{
    public function search(Request $request)
    {
    	if($request->has('search')){
    		$posts = Post::search($request->get('search'))->get();	
    	}else{
    		$posts = Post::get();
    	}
        return view('index', compact('posts'));
    }
}
Step 9: Create a View File

In this step, let's create index.blade.php(resources/views/index.blade.php) for layout and we will write design code here and also post search and recored table, So put following code:

following path:resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel Scout Search Tutorial </title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
</head>
<body>
    <div class="container">
        <h1>Laravel Scout Search Tutorial</h1>
        <div class="row">
            <div class="col-md-6">
                <form method="GET" action="{{ url('index') }}">
                    <div class="row">
                        <div class="col-md-10">
                            <input type="text" name="search" class="form-control" placeholder="Search">
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-info">Search</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="col-md-4 ">
                <a href="{{ url('index') }}" class="btn btn-danger">Cancel</a>
            </div>
        </div>
   <br/>
      <table class="table table-bordered">
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Body</th>
                <th>Category</th>
                <th>View</th>
            </tr>
            @if(count($posts) > 0)
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>{{ $post->body }}</td>
                    <td>{{ $post->category }}</td>
                    <td>{{ $post->view }}</td>
                </tr>
                @endforeach
            @else
            <tr>
                <td colspan="5" class="text-danger">Result not found.</td>
            </tr>
            @endif
        </table>
   </div>
</body>
</html>

Now we are ready to run our example so run bellow command so quick run:

php artisan serve
http://localhost:8000/index

It will help you...

Laravel Migration Add Comment to Column Example

Laravel Migration Add Comment to Column Example

Hi Dev,

Today, This blog is focused on laravel migration add comment to table. This tutorial will give you simple example of laravel migration add comment to table. i would like to show you laravel migration add comment to existing column.

laravel migration provide comment() where you can add comment to table column. so let's see both example. you can easily set laravel 8 version.

Create Table Column with Comment
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('rank')->comment("page rank detail");
            $table->integer('stock');
            $table->text('description');
            $table->timestamps();
        });
    }

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

Existing Table Column with Comment

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class AddNewColumnAdd2 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('pages', function (Blueprint $table) {
            $table->string('stock')->comment("Page stock detail")->change();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        
    }
}

It Will help You...

Laravel 8 Barcode Generator Example

Laravel 8 Barcode Generator Example

Hi Dev

Today,I will learn you how engender barcode in laravel 8 we will show barcode engenderer example in laravel 8.I will engenderer barcode useing milon/barcode package in laravel 8. laravel 8 barcode engenderer example. in this tutorial, i would relish to show you how to engender or engender barcode in laravel 8 utilizing milon/barcode package.

In this blog, i will utilize milon/barcode package to engender simple, text, numeric and image barcode in laravel 8 app.

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Step 2 :Database Configuration

In this step, configure database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3 :Installing Barcode Generator Package

Now In this step, install milon/barcode package in laravel 8 app via following command.

composer require milon/barcode
Step 4:Configure Barcode Generator Package

Here In this step,I will configure the milon/barcode package in laravel 8 app. So, Open the providers/config/app.php file and register the provider and aliases for milon/barcode.

'providers' => [
    ....
    Milon\Barcode\BarcodeServiceProvider::class,
],
  
'aliases' => [
    ....
    'DNS1D' => Milon\Barcode\Facades\DNS1DFacade::class,
    'DNS2D' => Milon\Barcode\Facades\DNS2DFacade::class,
]
Step 5:Create Routes

In this step,we will add the bar code generation routes in web.php file, which is located inside routes directory:

use App\Http\Controllers\BarcodeController;
Route::get('/barcode', [BarcodeController::class, 'index'])->name('barcode.index');
Step 6: Creating BarCode Controller

Now this step,I will create generate barcode controller file by using the following command.

php artisan make:controller BarCodeController

After navigate to app/http/controllers and open BarCodeController.php file. And add the simple barcode generation code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BarcodeController extends Controller
{
    public function index()
    {
      return view('barcode');
    }
}
Step 7 :Create Blade View

In this last step , create barcode-generator blade view file inside resources/views directory. And then add the following code into it.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Barcode Generator</title>
</head>
<body>
<div class="container text-center">
  <div class="row">
    <div class="col-md-8 offset-md-2">
       <h1 class="mb-5">Laravel 8 Barcode Generator</h1>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'C39') !!}</div></br>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'POSTNET') !!}</div></br>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'PHARMA') !!}</div></br>
       <div>{!! DNS2D::getBarcodeHTML('4445645656', 'QRCODE') !!}</div></br>
    </div>
  </div>
</div>
</body>
</html>

Now we are ready to run our custom validation rules example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/barcode

It will help you..

Laravel 8 Login with Github Example

laravel 8 login with Github account

Hi Men

These days, I can give an explanation for you step by step login with Github Account in laravel 8 the usage of socialite. laravel eight socialite provide api to login with github account. you could effortlessly login using Github in laravel eight utility.

As we realize social media is a turn out to be increasingly popular inside the global. each one have social account like github, facebook and so forth. i suppose also most of have github account. So if for your utility have login with social then it grow to be exceptional. to procure more humans hook up with your website because most of human beings does not need to fill sign on or check in form. If there login with social than it end up splendid.

So in case you want to also enforce login with github account then i can assist you grade by grade education. let's comply with educational and implement it.

Step 1 : Install Laravel 8

Inside the first step, we need to get clean laravel 8 model software So permit's open terminal and run bellow command to put in clean laravel assignment.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration as an instance database call, username, password and many others. So we could open .env record and fill all deatils like as bellow:

.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 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4 : Install Socialite In this step, we need laravel/socialite package. you can install socialite package using bellow command so let's run bellow command :
composer require laravel/socialite

After install above package you can add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

config/app.php
....

'providers' => [
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

....
Step 5: Create Github Api

Here we need Github account that way we can get information of other user. so if you don't have Github account then you can create from here : Github. you can find bellow screen :

Laravel 8 Login with Github Example

Now you have to click on Developer settings

Laravel 8 Login with Github

Next you have to click on OAuth Apps

laravel 8 socialite Github login

Here you have to click on Register a new application

 Github login with laravel 8

Here you have to create on Register a new OAuth application

login with gmail laravel 8

Now Redy Github APi

laravel 8 socialite Github tutorial

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php
	return [
    ....
    'github' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://your-callback-url',
    ],
]
Step 6: Add Database Column

In this step first we have to create migration for add Github Id in your user table. So let's run bellow command:

php artisan make:migration add_github_id_column
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGithubIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('github_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('github_id');
         });
    }
}
Update mode like this way: app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 7: Create Routes

Here, we need to add resource route for login with gmail account. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\GithubController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('auth/github', [GithubController::class, 'redirectToGithub']);
Route::get('auth/github/callback', [GithubController::class, 'handleGithubCallback']);
Step 8: Create Controller

After add route, we need to add method of github auth that method will handle github callback url and etc, first put bellow code on your GithubController.php file

app/Http/Controllers/Auth/GithubController.php
<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class GithubController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGithub()
    {
        return Socialite::driver('github')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGithubCallback()
    {
        try {
    
            $user = Socialite::driver('github')->user();
     
            $finduser = User::where('github_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/home');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'github_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/home');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 9: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                <a href="{{ url('auth/github') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2">
                  <strong>Login With Github</strong>
                </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>
Now we are ready to run our form validation example with laravel 8 so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
localhost:8000/login
You will see layout as like bellow: Output
socialite Github laravel 8

It will help you...

React Native Paper Menu Tutorial

React Native Paper Menu Tutorial

Hi Guys,

Today, I'm able to study you a way to engender paper menu in react native. you can facilely engender paper menu in react native. First i will import stylesheet namespace from react-local-paper, after i can make paper menu utilizing in react native.

Here, I can give you full instance for simply exhibit paper menu using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init PaperMenu
Step 2 - Install Package

In the step,I will install npm i react-native-paper package.

npm i react-native-paper
Step 3 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";
import { Text, View,StyleSheet} from 'react-native';
import { Provider ,Appbar,Card,menu} from 'react-native-paper';

const ItWebtutsComponent = () => {

   const [searchQuery, setSearchQuery] = React.useState('');

  const onChangeSearch = query => setSearchQuery(query);

  const _goBack = () => console.log('Went back');

  const _handleSearch = () => console.log('Searching');

  const _handleMore = () => console.log('Shown more');

  return (
    <Provider>
    <Appbar.Header style={styles.header}>
      <Appbar.BackAction onPress={_goBack} />
      <Appbar.Content title="User" subtitle="Subtitle" />
      <Appbar.Action icon="magnify" onPress={_handleSearch} />
      <Appbar.Action icon="dots-vertical" onPress={_handleMore} />
    </Appbar.Header>
      <View style={styles.mainbox}>
       <Card>
        <menu
            placeholder="Search"
            onChangeText={onChangeSearch}
            value={searchQuery}
          />
       </Card>
      </View>
    </Provider>
  );
};


const styles = StyleSheet.create({
  title:{
    margin: 10,
    fontSize: 15,
    fontSize: 35
  },
  mainbox:{
    textAlign:'center',
    margin: 15,
    flex: 1,
    justifyContent: 'space-between',
  },
  databeBox:{
    margin: 10,
    textAlign: 'center',
  },
  databeHeader:{
    margin: 10,
    textAlign: 'left', 
  }
});
export default ItWebtutsComponent;
Step 4 - Run project

In the last step run your project using bellow command.

expo start

It will help you...