Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ranjeet's avatar

Check name availability using ajax

I have a form where user can add products with unique product name.I want to check live product name availability using ajax.Iam having problem

Route::group(['prefix'=>'admin','middleware'=>['auth','validIp']],function(){

Route::resource('product','Product\ProductController');
 
});

my from

{!! Form::text('name', null, ['class' => 'form-control','id'=>'name']) !!}

my controller http://localhost:8000/admin/product

 public function store(Request $request)
    {

        $product= new Product;  
        $name = $request->get('name');  
        $product->name = $request->get('name');
      

        $query = \DB::table('products')->select('name')
                 ->where('name','!=',$name)
                 ->get();
            if($query)
            {
                return"Username not available!";
            }
            return "Username available!";
       //......
    $product->save();

js

<SCRIPT type="text/javascript">



$(document).ready(function(){

$("#name").change(function() { 

var usrN = $("#name").val();

if(usrN.length >= 4)
{
$("#statuspass").html('<img src="images/loadingAnimation.gif"> Checking ...');

    $.ajax({  
    type: "POST",  
     url : base_url+"/admin/product", 
    data: "name="+ usrN, 
    success: function(msg){  
   
   $("#statuspass").ajaxComplete(function(event, request, settings){ 

    if(msg == 'OK')
    { 
        $("#name").removeClass('object_error'); 
        $("#name").addClass("object_ok");
        $(this).html('<img src="images/success.png" align="absmiddle"> OK<');
    }  
    else  
    {  
        $("#name").removeClass('object_ok'); 
        $("#name").addClass("object_error");
        $(this).html(msg);
    }  
   
   });

 } 
   
  }); 

}
else
    {
    $("#statuspass").html('<font color="red" style="margin-left:125px;">something went wrong <strong></strong> .</font>');
    $("#name").removeClass('object_ok'); 
    $("#name").addClass("object_error");
    }

});

});


</SCRIPT>

In Plain PHP i used to do something like this

say checking.php
<?php

$conn = mysql_connect("localhost", "root", "");
mysql_select_db("videobox", $conn);


if(isSet($_POST['email']))

{

$email = $_POST['email'];



$sql_check = mysql_query("select id from users where email='".$email."'") or die(mysql_error());



if(mysql_num_rows($sql_check))

{

echo '<font color="red" style="margin-left:105px;"><STRONG>'.$email.'</STRONG> is not available.</font>';

}

else

{

echo 'OK';

}



}



?>

and in js i just used to do url: "checking.php", How can i achieve this in laravel

0 likes
16 replies
bobbybouwmann's avatar

You can create an additional route in Laravel and you can add a function in your controller for that route. Your function might look like this

public function checkName(Request $request)
{
    // This will either return a full Product object or NULL
    return Product::where('name', '=', $request->get('name'))->first();
}

You can now check for null in the ajax response

Corez64's avatar

You need to move your checking.php into a method in your controller. Then you need to add a route so that the check will be run

Route::group(['prefix'=>'admin','middleware'=>['auth','validIp']],function(){
    Route::get('product/check', 'Product\ProductController@check');
    Route::resource('product', 'Product\ProductController'); 
});
class ProductController extends Controller
{
    // ...

    public function check($email)
    {
        if (Product::where('email', $email)->first()) {
            return '<font color="red" style="margin-left:105px;"><STRONG>'.$email.'</STRONG> is not available.</font>';
        }

        return 'OK';
    }

    // ...
}
Ranjeet's avatar

@bobbybouwmann -I have followed your steps

made route like this

Route::group(['prefix'=>'admin','middleware'=>['auth','validIp']],function(){
Route::get('name','Product\ProductController@checkName');

//....
});
public function checkName(Request $request)
{
    //iam here
    // This will either return a full Product object or NULL
    return Product::where('name', '=', $request->get('name'))->first();
}

But i have not got any thing in url http://localhost:8000/admin/name,whit blank page i got

bobbybouwmann's avatar

You need to make a post request from your ajax call, something like this

// routes.php
Route::post('product/name', ['Product\ProductController@checkName');

// JavaScript
$.ajax({
    method: 'POST',
    url: '/product/name',
    data: {
        name: $('input').val() // Get the value of the input
    }
}).done(function (response) {
    // Check if response is null or not
    // Based on that continue the process or show a message or something
});
1 like
Ranjeet's avatar

@Corez64 i got error Missing argument 1 for App\Http\Controllers\Product\ProductController::check()

i have to get $name from user input not by route something like this

public function store(Request $request){
$product=new Product;
$name=$request->get('name');
//............
}
public function check(Request $request){

how can i get above $name here,in this function
}
Ranjeet's avatar

@bobbybouwmann my js is same as above i have mention and i have change url:/product/name as you have written above and controller is


 public function checkName(Request $request)
{
 
    return product::where('name', '=', $request->get('name'))->first();
}
bobbybouwmann's avatar

Did you import the class path of the Request class?

use Illuminate\Http\Request;
bobbybouwmann's avatar

Should work fine, what do you get when you do this?

public function checkName(Request $request)
{
    dd($request->all();
}

Also, you do have this function in your controller right?

Ranjeet's avatar

i got[] on doing dd($request->all(); i have not got anything

bobbybouwmann's avatar

You don't post anything. You need to get the data from the input field and and set that in the post request with ajax like I showed you before

data: {
    name: (Grab here the value from the input)
}
Ranjeet's avatar

@bobbybouwmann it is possible to get Request $request of one Controller of certain function to another or same controller of another function as below.How?

//say this function has a form in view with input field text and name=name inside<form>...</form>
public function store(Request $request){
$product=new Product;
$name=$request->get('name');
//............
}
//This function  checkName doesnot have a form,can i get above request here ,how??
public function checkName(Request $request){
dd($request->get('name');
how can i get above $name here,in this function
}
bobbybouwmann's avatar

You can simply do this

public function store(Request $request) {
    $this->checkName($name);
}

public function checkName($name) {
    dd($name);
}
Ranjeet's avatar

public function checkName($name) $name should come from route yes or no?

bobbybouwmann's avatar

It depends on your needs.. You clearly don't know the basics of Laravel or jQuery (ajax requests). I suggest you to learn those first before you continue!

Please or to participate in this conversation.