Part I:

Sometimes you may need to make the whole CRUD operation just in one page without reloading or navigating to another page. Live Table CRUD in Laravel can be succeeded by using Ajax.

For this course I imagine that you have already finished setting up database connectivity and your application is up. If you haven’t finished setting up you can read this article that covers all about MySQL DB Connectivity and Table manipulation on laravel

Let’s start by creating a table named Books.

php artisan make:migration create_books_table

After running the above command our new migration file will be created inside â€˜database/migrations’. after I added the needed columns the content will look like:

<?php

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

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

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

Now run the migrate command to create the table

php artisan migrate

After migration create model and controller. Then declare its route in web.php

  • CREATE MODEL
php artisan make:model Book -m
  • CREATE CONROLLER
php artisan make:controller BookController --resource
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Book; //is the model
use DB;

class BookController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function index(Request $request)
    { 
        $books = Book::all()->toArray(); 
        return view('book.index',compact('books'));
    }
}
Route::resource('kutub','KutubController');
  • Create View: create index.blade.php inside /resources/view/book directory and paste the following code.
{{ csrf_field() }}
<div id="message"></div>
<table class="table table-bordered table-striped">
<tr> 												 
       <th>Name</th>
       <th>Author</th>
       <th>Description</th> 
       <th>Action</th> 
</tr>
<tr> 										                                  
       <td contenteditable="true" id="name"></td>
       <td contenteditable="true" id="author"></td>					       
       <td contenteditable="true" id="description"></td>									       
       <td><button class="btn btn-success" id="add"><i class="fa fa-plus-square"> 
       </i>Add</button></td>									</tr>
@foreach ($books as $book)										 
   <tr> 	
      <td>{{$book['name']}}</td>										 
      <td>{{$book['author']}}</td>
      <td>{{$book['description']}}</td>
     <td><a id="{{$book['id']}}" style="color:white" class="delete btn btn-danger"><i class="fa fa-trash-o"></i></a></td>
   </tr>    
@endforeach
</table> 

I have successfully created the HTML table.

Live CRUD Operation: Create

Now, Let’s see how to insert a record to the database. As you see I have a td tag with contenteditable="true" attribute. This makes the <td></td> tag to be editable. Also I have set the id of each field so that I can get its value by its id. I have a button Add button. Next, the following is a Javascript code that listen onclick event of the add button. Also don’t forget to have a jquery plugin.

<script src="{{ asset('js/jquery.min.js') }}"></script>
<script type="text/javascript">
  jQuery(document).ready(function(){
    var _token = $('input[name="_token"]').val();
    $(document).on('click','#add',function(){ 
	var name = $('#name').text(); 
	var author = $('#author').text(); 
	var description = $('#description').text();  
	console.log();
	if(name != ''){
		$.ajax({
			url:"{{ route('book.store') }}", 
			method:"POST",
			data:{name:name,author:author,description:description,_token:_token},
			success:function(data){ 
				$('#message').html(data);
				//window.location.reload();
			}
		});
	}else{
$('#message').html("<div class='alert alert-danger'> Name field is required</div>");
	}
});
  });	
</script>

Yes, This is the javascript code that will be executed when the Add button clicked. The URL “{{ route(‘book.store’) }}”, As I explained above this route is defined in web.php inside /routes directory.

Now let’s write the code for store function in BookController.php

    public function store(Request $request)
    {  
        if($request -> ajax())
        { 
            $data = array(
                'name' => $request ->name,
                'author' => $request ->author,
                'description'=> $request ->description, 
            );
            $id = DB::table('users')->insert($data); 
            if($id > 0){
                echo '<div class="alert alert-success">Book Crated Successfully!</div>';
            }else{
                echo '<div class="alert alert-danger">Error while creating the book!</div>';
            }
        }
    }

After saving your project run it by using the following artisan command

php artisan serve

Then, navigate to http://127.0.0.1:8000/book/ if you are testing locally. After that fill all fields and click click the add button.

Finally, I have inserted successfully.


The part II of this lesson found here.

Categories: LaravelPHPWeb

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *