Laravel search result is too slow

I need to build search functionality in my website. So far I have implemented the query in eloquent. It is like this,

I need to build search functionality in my website. So far I have implemented the query in eloquent. It is like this,

`$syukko = Syukko::where('category',  $cat)
->where('status', 1)
->get();`

Now, this website may have a large database. My tester tested it and reported that, it was performing too slow. I tried to use paginate to show 20 results per page. Still the speed was not improving.

One colleague suggested me to use AJAX. My question is does AJAX search perform faster than basic eloquent in pgsql? (live search is not necessary)

Also, currently I don't have large database with my machine. I write the code and send it to tester. Can I use any tool to get query time in localhost?

Laravel 6 Ajax Request Tutorial

Laravel 6 Ajax Request Tutorial

In this post, you'll learn how to write jquery ajax form submit in Laravel 6. We will write Jquery Ajax post request Laravel 6. We will protect csrf token with Ajax request in Laravel 6. I will give you very simple example of Laravel 6 Ajax post request tutorial.

You can easily use Ajax get request, Ajax post request, Ajax put request, Ajax delete request ect with Laravel 6.

Ajax request is a basic requirement of any PHP project, we are always looking for without page refresh data should store in database and it's possible only by Jquery Ajax request. same thing if you need to write ajax form submit in Laravel 6 then i will help you how you can pass data with ajax request and get on controller.

If you want to add ajax request with validation then you can follow this article: Laravel 6 Ajax Form Validation

You have to just do three things to understand how to use ajax request in Laravel 6, so just follow this three step and you will learn how to use Ajax request in your Laravel 6 application.

Step 1: Create Routes

First thing is we put two routes in one for displaying view and another for post Ajax. So simple add both routes in your route file.

routes/web.php

Route::get('ajaxRequest', '[email protected]');
Route::post('ajaxRequest', '[email protected]')->name('ajaxRequest.post');

Step 2: Create Controller

Same things as above for routes, here we will add two new method for routes. One will handle view layout and another for post ajax request method, so let's add bellow:

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function ajaxRequestPost(Request $request)
{
    $input = $request-&gt;all();
    \Log::info($input);

    return response()-&gt;json(['success'=&gt;'Got Simple Ajax Request.']);
}

}

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Create Blade File

Finally we require to create ajaxRequest.blade.php file and here we will write code of jquery ajax and pass Laravel token. So blade file is very important in ajax request. So let's see bellow file:

resources/views/ajaxRequest.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 Ajax Request example</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>

&lt;div class="container"&gt;
    &lt;h1&gt;Laravel 6 Ajax Request example&lt;/h1&gt;

    &lt;form &gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Name:&lt;/label&gt;
            &lt;input type="text" name="name" class="form-control" placeholder="Name" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Password:&lt;/label&gt;
            &lt;input type="password" name="password" class="form-control" placeholder="Password" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;strong&gt;Email:&lt;/strong&gt;
            &lt;input type="email" name="email" class="form-control" placeholder="Email" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;button class="btn btn-success btn-submit"&gt;Submit&lt;/button&gt;
        &lt;/div&gt;

    &lt;/form&gt;
&lt;/div&gt;

</body>
<script type="text/javascript">

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".btn-submit").click(function(e){

    e.preventDefault();

    var name = $("input[name=name]").val();
    var password = $("input[name=password]").val();
    var email = $("input[name=email]").val();

    $.ajax({
       type:'POST',
       url:"{{ route('ajaxRequest.post') }}",
       data:{name:name, password:password, email:email},
       success:function(data){
          alert(data.success);
       }
    });

});

</script>

</html>

Now you can run your example and see.

You will get output like as bellow:

Output

[2019-09-17 03:54:19] local.INFO: array (
'name' => 'Hardik Savani',
'password' => '123456',
'email' => '[email protected]',
)

I hope it can help you

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

☞ Tutorial Laravel 6 with Docker and Docker-Compose

☞ Laravel 6 CRUD Application Tutorial

☞ What's New in Laravel 6.0?

Originally published https://itsolutionstuff.com


How to image upload using Ajax in Laravel 6

How to image upload using Ajax in Laravel 6

In this post, you will learn how to image upload using Ajax in Laravel 6 App. I write simple tutorial of Laravel 6 Ajax image upload with validation. We will use Jquery form js for Ajax image upload in Laravel 6.

Here I give you full example of Ajax image uploading step by step like create laravel project, migration, model, route, blade file etc. So you have to just follow few steps.

Not issue if you don't know laravel because it is from scratch. After complete this example you will find bellow as like preview, so let's start.

Step 1 : Install Laravel 6 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, 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:

.env

DB_HOST=localhost

DB_DATABASE=homestead

DB_USERNAME=homestead

DB_PASSWORD=secret

Read Also: Laravel 6 Ajax CRUD Operations Tutorial

Step 3: Create ajax_images Table and Model

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

php artisan make:migration create_ajax_image_tabel

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create categories table.

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateAjaxImageTabel extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('ajax_images', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('title');

            $table->string('image');

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::drop("ajax_images");

    }

}

Now we require to run migration be bellow command:

php artisan migrate

After create "ajax_images" table you should create AjaxImage model for categories. So first we have to run bellow laravel artisan command for create AjaxImage model:

php artisan make:model AjaxImage

Now, you can see new file on this path app/AjaxImage.php and put bellow content in item.php file:

app/AjaxImage.php

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class AjaxImage 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. so open your routes/web.php file and add following route.

routes/web.php

Route::get('ajaxImageUpload', '[email protected]');

Route::post('ajaxImageUpload', '[email protected]')->name('ajaxImageUpload');
Step 5: Create Controller

In this point, now we should create new controller as AjaxImageUploadController in this path app/Http/Controllers/AjaxImageUploadController.php. this controller will manage layout and image validation with post request, So run bellow command for generate new controller:

php artisan make:controller AjaxImageUploadController

Ok, now put bellow content in controller file:

app/Http/Controllers/AjaxImageUploadController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Validator;

use App\AjaxImage;


class AjaxImageUploadController extends Controller

{

	/**

     * Show the application ajaxImageUpload.

     *

     * @return \Illuminate\Http\Response

     */

    public function ajaxImageUpload()

    {

    	return view('ajaxImageUpload');

    }


    /**

     * Show the application ajaxImageUploadPost.

     *

     * @return \Illuminate\Http\Response

     */

    public function ajaxImageUploadPost(Request $request)

    {

      $validator = Validator::make($request->all(), [

        'title' => 'required',

        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

      ]);


      if ($validator->passes()) {


        $input = $request->all();

        $input['image'] = time().'.'.$request->image->extension();

        $request->image->move(public_path('images'), $input['image']);


        AjaxImage::create($input);


        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/ajaxImageUpload.blade.php) for layout and we will write design code here and also form for ajax image upload, So put following code:

resources/views/ajaxImageUpload.blade.php

<!DOCTYPE html>

<html>

<head>

	<title>Laravel 5 - 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>

	<script src="http://malsup.github.com/jquery.form.js"></script>

</head>

<body>


<div class="container">

  <h1>Laravel 5 - Ajax Image Uploading Tutorial</h1>


  <form action="{{ route('ajaxImageUpload') }}" 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>Alt 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>


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

Make sure you have to create "images" folder in your public directory.

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:

Read Also: Laravel 6 Authentication Tutorial

http://localhost:8000/ajaxImageUpload

I hope it can help you...

How to use Ajax form validation in Laravel 6

How to use Ajax form validation in Laravel 6

In this tutorial, I would like to guide how to use Aajax form validation in Laravel 6. We will use Laravel 6 validation with ajax post request. We will gives errors response and display it on front side using Ajax Laravel 6

Originally published at https://itsolutionstuff.com

Form validation is a basic requirement of any form. We should implement validation even if you use Ajax or simple form. But if you are working with Jquery Ajax then you can use also server side validation using Laravel and display error messages on front side.

You can simply use Laravel 6 validation like required, email, same, unique, date, integer etc using Jquery Ajax post, get, put or delete request. We will use Validator make function for create validation and check using passes() function.

In this example i will show you how to use Laravel default validation with Jquery Ajax. Here we also print Laravel validation message when false. So if you want to ajax form validation in Laravel app then you are right place.

Just follow bellow step to create ajax validation example:

Step 1: Add Route

In first step we will create new two routes for demo. so open your routes/web.php file and add following route.

routes/web.php

Route::get('my-form','[email protected]');
Route::post('my-form','[email protected]')->name('my.form');

Step 2: Create Controller

In this point, now we should create new controller as HomeController. So run bellow command and create new controller.

php artisan make:controller HomeController

After bellow command you will find new file in this path app/Http/Controllers/HomeController.php.

In this controller we will write three method for ajax view and post as listed bellow methods:

1) myform()

2) myformPost()

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

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class HomeController extends Controller
{

/**
 * Display a listing of the myform.
 *
 * @return \Illuminate\Http\Response
 */
public function myform()
{
	return view('myform');
}
 
/**
 * Display a listing of the myformPost.
 *
 * @return \Illuminate\Http\Response
 */
public function myformPost(Request $request)
{
 
	$validator = Validator::make($request-&gt;all(), [
        'first_name' =&gt; 'required',
        'last_name' =&gt; 'required',
        'email' =&gt; 'required|email',
        'address' =&gt; 'required',
    ]);
 
    if ($validator-&gt;passes()) {
        return response()-&gt;json(['success'=&gt;'Added new records.']);
    }
 
    return response()-&gt;json(['error'=&gt;$validator-&gt;errors()-&gt;all()]);
}

}

Read Also: Laravel 6 Release New Features and Upgrade

Step 3: Create View File

In Last step, let's create myform.blade.php(resources/views/myform.blade.php) for layout and we will write design code and jquery ajax code,so put following code:

resources/views/myform.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 Ajax Validation Example - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>

<div class="container">
<h2>Laravel 6 Ajax Validation - ItSolutionStuff.com</h2>

&lt;div class="alert alert-danger print-error-msg" style="display:none"&gt;
    &lt;ul&gt;&lt;/ul&gt;
&lt;/div&gt;
   
&lt;form&gt;
    {{ csrf_field() }}
    &lt;div class="form-group"&gt;
        &lt;label&gt;First Name:&lt;/label&gt;
        &lt;input type="text" name="first_name" class="form-control" placeholder="First Name"&gt;
    &lt;/div&gt;
   
    &lt;div class="form-group"&gt;
        &lt;label&gt;Last Name:&lt;/label&gt;
        &lt;input type="text" name="last_name" class="form-control" placeholder="Last Name"&gt;
    &lt;/div&gt;
   
    &lt;div class="form-group"&gt;
        &lt;strong&gt;Email:&lt;/strong&gt;
        &lt;input type="text" name="email" class="form-control" placeholder="Email"&gt;
    &lt;/div&gt;
   
    &lt;div class="form-group"&gt;
        &lt;strong&gt;Address:&lt;/strong&gt;
        &lt;textarea class="form-control" name="address" placeholder="Address"&gt;&lt;/textarea&gt;
    &lt;/div&gt;
   
    &lt;div class="form-group"&gt;
        &lt;button class="btn btn-success btn-submit"&gt;Submit&lt;/button&gt;
    &lt;/div&gt;
&lt;/form&gt;

</div>

<script type="text/javascript">

$(document).ready(function() {
    $(".btn-submit").click(function(e){
        e.preventDefault();
   
        var _token = $("input[name='_token']").val();
        var first_name = $("input[name='first_name']").val();
        var last_name = $("input[name='last_name']").val();
        var email = $("input[name='email']").val();
        var address = $("textarea[name='address']").val();
   
        $.ajax({
            url: "{{ route('my.form') }}",
            type:'POST',
            data: {_token:_token, first_name:first_name, last_name:last_name, email:email, address:address},
            success: function(data) {
                if($.isEmptyObject(data.error)){
                    alert(data.success);
                }else{
                    printErrorMsg(data.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('&lt;li&gt;'+value+'&lt;/li&gt;');
        });
    }
});

</script>

</body>
</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:

Read Also: Laravel 6 Authentication Tutorial

http://localhost:8000/my-form

I hope it can help you...

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

What’s New in Laravel 6.0

Laravel 6 CRUD Application Tutorial

Laravel 6 Image Upload Tutorial

Laravel 6 Authentication Tutorial

Laravel 6 Social Login Tutorial - Login with Github