Chanon Saelee Chanon Saelee - 4 months ago 101
PHP Question

How to add multiple field of AutoComplete with Laravel 5.2

I'm new for Laravel 5.2 and I want to create user search with autocomplete to add many user to use an article or something.
Now I have found some of example for autocomplete and that's work fine.
But I want to add another search field for add another user and choose role for each user to that article.

Please help me to find the solution or some advice to make it possible.
Thank you.

This is my code

index.blade.php

{{ Form::open(['action' => ['SearchController@autocomplete'], 'method' => 'GET']) }}
{{ Form::text('q1', '', ['id' => 'q1', 'class' => 'form-control', 'style' => 'width:250px', 'placeholder' => 'Search users']) }}
{{ Form::close() }}


JS

<script>
$(function()
{
$( "#q1" ).autocomplete({
source: "{{ url('search/autocomplete') }}",
minLength: 3,
select: function(event, ui) {
// $('#q').val(ui.item.value);
event.preventDefault()
$('#q1').val(ui.item.name);
}//end select
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + " : " + item.email + "</a>")
.appendTo(ul);
};
});
</script>


SearchController

class SearchController extends Controller
{
public function autocomplete(){
$term = Input::get('term');

$results = array();

$queries = DB::table('users')
->where('name', 'LIKE', '%'.$term.'%')
->orWhere('email', 'LIKE', '%'.$term.'%')
->take(10)->get();

foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'name' => $query->name, 'email' => $query->email ];
}
return Response::json($results);
}

}


UPDATE SCHEMA
Now it still a draft and not sure about detail fields.
but I think I have some Table like this


User Table > for stored userID and username and more.


Exam Table > for store examID and more... (This table for create an examID to add many user for test the exam and store userID , examID
to Coordinate Table)


Coordinate Table (Coordinate Model) > for store an examID and all of userIDs and userRole has recieve by your code and have field like
below (role maybe change to textNOTE)

id | exam_id | user_id | role


Answer

As I understand your problem, you want to add the user and its role repeatedly without refreshing the page. Assuming this is the case you can follow following steps.

Note: below code is the minimal illustration to clarify the steps.

Role Model :- (Stored in App\Models directory)(assuming you have diffrent roles table)

<?php    
namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Role extends Model
{
    protected $fillable = ['role'];

    public function User(){
      return $this->belongsTo('App\Models\User');
    }
}

User Controller :- (Stored in App\HTTP\Controllers directory)
To handle add request and inset the data in DB

<?php

namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Role;

use Illuminate\Http\Request;
use DB;

class userController extends Controller
{

    public static function addRole(Request $request)
    {
         User::where('id',$request->user_id)
               ->Role()
               ->create($request->only(['role']));        
        }
    }

Add a route to handle the request:-

Route::post('/add/user', array('uses' => 'userController@addUser'));

Add a form in your View which will add the user:

{{ Form::open(['action' => ['userController@addUser'], 'method' => 'POST','id'=>'add_role_form']) }}
   {{ Form::hidden('id', '', array('id' => 'id','class' => 'form-control')) }}
   {{ Form::text('name', '', ['id' =>  'name', 'class' => 'form-control', 'placeholder' =>  'Search users','disabled' => 'disabled']) }}
   {{ Form::select('role', array('admin' => 'Admin', 'Editor' => 'Editor'),['id' =>  'role', 'class' => 'form-control']); }}
{{Form::button('Click Me!','id' =>  'addRole', 'class' => 'btn btn-primary','obclick'=>'addRole();'])}}
    {{ Form::close() }}

JS to add user role using ajax:

<script>
function addRole(){
$('#add_role_form').preventDefault()
        $.ajax({
            type: "POST",
            url: $('#add_role_form').attr('action'),
            data: $('#add_role_form').serialize(),
            cache: false,
            success: function(result){
                // Do something
            },
            error: function (result) {
                // Do something
            }
        });
    }
</script>

PS: Please add a JS script to assign user_id of selected user to hidden id filed in #add_role_form.

UPDATE:

HTML

<html>
    <head>
        <title>Test Form</title>

        <script src="js/jquery-2.2.4.js"></script>

        <script src="js/jquery.autocomplete.js"></script>

        <script>
            $(document).ready(function () {
                console.log($('#userForm input:last'));
                var user = Array('User1','User2','User3','User4','User5','User6');<!-- User data. Not required if serviceUrl option is provided-->
                $('#user').autocomplete({
                    lookup: user, <!-- Use user variable as data source. Not required if serviceUrl option is provided for ajax request -->
                    tabDisabled:true,
                    showNoSuggestionNotice:true,
                        onSelect: function (suggestion) {
                    }
                });
                var role = Array('Role1','Role2','Role3','Role4','Role5','Role6');<!-- Role data. Not required if serviceUrl option is provided-->
                $('#role').autocomplete({
                    lookup: role, <!-- Use role variable as data source. Not required if serviceUrl option is provided for ajax request -->
                    tabDisabled:true,
                    showNoSuggestionNotice:true,
                    onSelect: function (suggestion) {
                    }
                });
            });
            var count = 0; <!-- Counter to keep track of elements i.e. user->role pairs -->
            function add(){<!-- Function to insert user and role pair as input to form -->
                $('#userForm input:last')
                        .before($('<label>')
                                .attr('for','data['+count+'][user]')
                                .text('User')
                        )
                        .before($('<input>')
                                .attr('type', 'text')
                                .attr('name','data['+count+'][user]')
                                .val($('#user').val())
                        )
                        .before($('<label>')
                                .attr('for','data['+count+'][role]')
                                .text('Role')
                        )
                        .before($('<input>')
                                .attr('type', 'text')
                                .attr('name','data['+count+'][role]')
                                .val($('#role').val())
                        )
                        .before($('<hr>'));
                count=count+1;
            }
        </script>

        <link media="all" type="text/css" rel="stylesheet" href="css/bootstrap.css">

        <link media="all" type="text/css" rel="stylesheet" href="css/font-awesome.css">

    </head>
    <body class="container">
    <div class="row"> 
        <div class="col-lg-6">
                <input type="text" id="user" class="form-control" placeholder="Search User" /><!-- User search field -->
        </div>
        <div class="col-lg-4">
                <input type="text" id="role" class="form-control" placeholder="Search Role" /><!-- Role search field. You can use Dropdown list instead of Input -->
        </div>
        <div class="col-lg-2">
            <a class="btn btn-info" onclick="add();">Add User</a> <!-- Button to add user -> role pair to form -->
        </div>
    </div>


    <form method="post" id="userForm" action="http://127.0.0.1/public/test"> <!-- user data form. This is going to be submited to server-->
        <input type="submit" name="submit" class="btn btn-primary"/>
    </form>

    </body>
</html>

ROUTE

// To get Form
Route::get('test',function (){
    return View::make('test');
});

// To handle Form
Route::post('test',function (Request $request){
    var_dump($request->all());
});

var_dump Output:

array (size=1)
  'data' => 
    array (size=5)
      0 => 
        array (size=2)
          'user' => string 'User1' (length=5)
          'role' => string 'Role1' (length=5)
      1 => 
        array (size=2)
          'user' => string 'User1' (length=5)
          'role' => string 'Role1' (length=5)
      2 => 
        array (size=2)
          'user' => string 'User1' (length=5)
          'role' => string 'Role1' (length=5)
      3 => 
        array (size=2)
          'user' => string 'User1' (length=5)
          'role' => string 'Role1' (length=5)
      4 => 
        array (size=2)
          'user' => string 'User1' (length=5)
          'role' => string 'Role1' (length=5)

Update 2:

Coordinate is your Model instance. And I'm considering `ID

public function add(Request $request){
    $data = $request->data;
    foreach ($data as $key=>$value){        
        $data[$key]['exam_id'] = unique();
    }

    Coordinate::create($data);
}
Comments