Sunday, September 27, 2020

Laravel 8 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination Example

 In this tutorial, we'll learn to build a CRUD example with Laravel 8, Bootstrap 4, jQuery, and Ajax.

We'll see by example how to perform Ajax CRUD operations in Laravel 8 with a bootstrap modal, datatable and pagination.

Using Ajax with Laravel 8 for CRUD Operations

We'll be using the jQuery ajax() method for sending Ajax requests.

We'll be using yajra datatable for creating a datatable.

  • Step 1 - Installing Laravel 8
  • Step 2 - Installing Yajra Datatable
  • Step 3 - Configuring a MySQL Database
  • Step 4 - Creating a Laravel 8 Migration
  • Step 5 - Adding a Laravel 8 Route
  • Step 6 - Adding a Laravel 8 Controller and Model
  • Step 7 - Adding a Blade Template View
  • Step 8 - Serving the Laravel 8 Application

Step 1 - Installing Laravel 8

Let's get started by installing Laravel 8 in our development machine.

Head to a new command-line interface and run the following command:

$ composer create-project --prefer-dist laravel/laravel ajax-crud-example

Step 2 - Installing Yajra Datatable

Next, let's install the yajra datatable package in our Laravel 8 project using following command:

$ composer require yajra/laravel-datatables-oracle

Next, you need to add it to the providers and aliases arrays:


'providers'  =>  [
    Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases'  =>  [

    'DataTables'  =>  Yajra\DataTables\Facades\DataTables::class,

]

Step 3 - Configuring a MySQL Database

Next, let's configure a MySQL database for our Laravel 7 project. Make sure you have created a database then go to the .env file and add the information for connecting to your database:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydb
DB_USERNAME= root
DB_PASSWORD= root

Step 4 - Creating a Laravel 8 Migration

Let's now create a migration file for a customers table. Head back to your terminal and run the following command:

$ php artisan make:migration create_customers_table --create=customers

Next, open the migration file in the database/migrations folder update it as follows to create a customers database table:

<?php

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

class  CreateCustomersTable  extends  Migration{

/**

* Run the migrations.

*

* @return void

*/

public  function up(){

    Schema::create('customers',  function  (Blueprint $table)  {
        $table->bigIncrements('id');
        $table->string('firstName');
        $table->string('lastName');
        $table->text('info');
        $table->timestamps();
    });

}

/**

* Reverse the migrations.

*

* @return void

*/

public  function down(){
    Schema::dropIfExists('customers');

}
}

Next, you can create the table in the database by running the following command:

$ php artisan migrate

Step 5 - Adding a Laravel 8 Route

Let's now create a Laravel 8 route for accessing the view.

Go to the routes/web.php file and add following resource route:

Route::resource('customers','CustomerController');

Step 6 - Adding a Laravel 8 Controller and Model

Head back to your terminal and run the following command to generate a controller:

$ php artisan controller:make CustomerController

Next, open the app/Http/Controllers/CustomerController.php file and update it as follows:

<?php

namespace App\Http\Controllers;

use App\Customer;
use Illuminate\Http\Request;
use DataTables;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        if ($request->ajax()) {
            $data = Customer::latest()->get();
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                           $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editCustomer">Edit</a>';

                           $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteCustomer">Delete</a>';

                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }

        return view('CustomerAjax');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Customer::updateOrCreate(['id' => $request->Customer_id],
                ['firstName' => $request->firstName, 'info' => $request->info]);        

        return response()->json(['success'=>'Customer saved successfully!']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Customer  $Customer
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $Customer = Customer::find($id);
        return response()->json($Customer);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Customer  $Customer
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Customer::find($id)->delete();

        return response()->json(['success'=>'Customer deleted!']);
    }
}

Generating a Laravel 8 Database Model

Next, let's generate a Customer database model using the following command:

$ php artisan make:model Customer

Next, open the app/Customer.php file and update it as follows:

<?php

namespace  App;

use  Illuminate\Database\Eloquent\Model;

class  Customer  extends  Model{

    protected $fillable =  [

        'firstName', 'lastName', 'info'

    ];

}

Step 7 - Adding a Blade Template View

Next, inside the resources/views/ folder, create customer.blade.php file and update it as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6 Ajax CRUD Example</title>
    <meta name="csrf-token" content="">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>

<div class="container">
    <h1>Laravel 6 Ajax CRUD </h1>
    <a class="btn btn-success" href="javascript:void(0)" id="createNewCustomer"> Create New Customer</a>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Details</th>
                <th width="280px">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="CustomerForm" name="CustomerForm" class="form-horizontal">
                   <input type="hidden" name="Customer_id" id="Customer_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Details</label>
                        <div class="col-sm-12">
                            <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                        </div>
                    </div>

                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>

<script type="text/javascript">
  $(function () {

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

    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'firstName', name: 'firstName'},
            {data: 'lastName', name: 'lastName'},
            {data: 'info', name: 'info'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });

    $('#createNewCustomer').click(function () {
        $('#saveBtn').val("create-Customer");
        $('#Customer_id').val('');
        $('#CustomerForm').trigger("reset");
        $('#modelHeading').html("Create New Customer");
        $('#ajaxModel').modal('show');
    });

    $('body').on('click', '.editCustomer', function () {
      var Customer_id = $(this).data('id');
      $.get("" +'/' + Customer_id +'/edit', function (data) {
          $('#modelHeading').html("Edit Customer");
          $('#saveBtn').val("edit-user");
          $('#ajaxModel').modal('show');
          $('#Customer_id').val(data.id);
          $('#name').val(data.name);
          $('#detail').val(data.detail);
      })
   });

    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');

        $.ajax({
          data: $('#CustomerForm').serialize(),
          url: "",
          type: "POST",
          dataType: 'json',
          success: function (data) {

              $('#CustomerForm').trigger("reset");
              $('#ajaxModel').modal('hide');
              table.draw();

          },
          error: function (data) {
              console.log('Error:', data);
              $('#saveBtn').html('Save Changes');
          }
      });
    });

    $('body').on('click', '.deleteCustomer', function () {

        var Customer_id = $(this).data("id");
        confirm("Are You sure want to delete !");

        $.ajax({
            type: "DELETE",
            url: ""+'/'+Customer_id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

  });
</script>
</html>

Step 8 - Serving the Laravel 8 Application

Head back to your terminal and run the following command:

$ php artisan serve

Laravel CORS

 

What is CORS?

CORS stands for Cross-origin resource sharing. The concept is related to the same origin policy which all browsers implement. In a nutshell, this policy says that a web site may not perform web requests to a different web site, or to be precise, “origin” (scheme, hostname, port number). CORS is a mechanism that can relax such restrictions. While the browser enforces restriction, CORS must be implemented on the server side to let the browser know that it may relax the restrictions.

Let’s get started

Using your Terminal or command prompt, navigate to your project’s root directory and run the following artisan command:

php artisan make:middleware corsMiddleware

That command will create a middleware file in /app/Http/Middleware, now open the new file in editor and add the following code

<?phpnamespace App\Http\Middleware;use Closure;class corsMiddleware{/*** @param $request* @param Closure $next* @return mixed*/public function handle($request, Closure $next) {$response = $next($request);$response->headers->set('Access-Control-Allow-Origin' , '*');$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application','ip');return $response;}}

Now go to /app/Http/Kernel.php, add the following line to the $middleware array:

\App\Http\Middleware\corsMiddleware::class

After that add the bellow line to the $routeMiddleware array inside the same directory /app/Http/Kernel.php

‘cors’ => \App\Http\Middleware\CORS::class,

And that’s it, now the corsMiddleware is ready to use, here is an example how to use it in your routes :

Route::group([‘prefix’ => ‘auth’, ‘middleware’ => ‘cors’], function() {Route::post(‘/login’, ‘AuthController@login’);Route::post(‘/register’, ‘AuthController@register’);});

Tuesday, September 8, 2020

Laravel Model Events observer

 Laravel’s Eloquent ORM is the rock-solid implementation of Active Record. Apart from other awesome features offered by Laravel Eloquent, Laravel implements Observer Pattern to fire some events, which can be listened to hook into, when various actions are performed on a model.

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. Source : Wikipedia

In this post, we will be learning about Laravel’s model events and how we can create model observers for grouping event listeners.

Laravel Model Events

If you have used Laravel for a medium to large scale project, you might have encountered a situation where you want to perform some action while your Eloquent model is processing. Laravel’s Eloquent provide a convenient way to add your own action while the model is completing or has completed some action.

For example, if you have Post model and you want to set post slug automatically when a post is created. You can listen to the saving event and set the post slug like below:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';

    protected $fillable = ['title', 'slug', 'content'];

    protected static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            $model->slug = str_slug($model->title);
        });
    }
}

Eloquent provides a handful of events to monitor the model state which are:

  • retrieved : after a record has been retrieved.
  • creating : before a record has been created.
  • created : after a record has been created.
  • updating : before a record is updated.
  • updated : after a record has been updated.
  • saving : before a record is saved (either created or updated).
  • saved : after a record has been saved (either created or updated).
  • deleting : before a record is deleted or soft-deleted.
  • deleted : after a record has been deleted or soft-deleted.
  • restoring : before a soft-deleted record is going to be restored.
  • restored : after a soft-deleted record has been restored.

Sunday, September 6, 2020

Phpmyadmin installation for Deepin/ debian linux

 https://phoenixnap.com/kb/how-to-install-phpmyadmin-on-debian-10

Phpmyadmin localhost cant access issue solved

in apache2 config file 

$cfg['Servers'][$i]['auth_type'] = 'config';

$cfg['Servers'][$i]['username'] = 'root';
$cfg['Servers'][$i]['password'] = '';



virtual host setup for linux

 I have been doing Javascript programming for last 2 months, and haven’t worked on any Laravel application in that time. And when, on this weekend, I tried installing a laravel application, I forgot how to create the virtual host file for it. Because for every application, I like to use a domain, and NOT localhost:port. And I will tell you why we need to do make a domain for your applications.

Why do we need a domain?

As good as the php artisan serve command is, it is not going to be responsible for running your application in production mode.

If you have a virtual host setup for your application, let’s say test.site, it will tell your apache server in your machine to act as your server for your application, and you now don’t need to run the serve command and your application is still running.

And the serve command will try to run your application with it’s own settings, and when you move to a server, you will end up with many requirements that you need in order to host your application, and you wouldn’t know about that until you are actually installing your application on a real server.

So, having a real server on your side and running your application on it, gives you a heads up, on what would you need in order to run your application on a real server.

Let’s start with creating a virtual host file.

Virtual Host

It is just a symlink to your application which can be accessed via your link, in this case, test.site .

You can find these files inside your /etc/apache2/sites-available folder.

For example let’s create a virtual host file for a laravel application kept in /var/www/html/test

First go to, /etc/apache2/sites-available/ , copy 000-default.conf file or create a new file at that location with the name of the domain you want, i.e., test.site.conf .

Now, for the content of this file, I have created a ,

<VirtualHost *:80>
ServerAdmin admin@server.in
ServerName server.in
ServerAlias server.in
<Directory /var/www/html/project/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
DocumentRoot /var/www/html/project/public/
ErrorLog /var/www/html/project/error.log
CustomLog /var/www/html/project/access.log combined
</VirtualHost>

 from which you can copy the content and paste in the file. Now you can replace the things as you desire.

ServerAdmin — It can be any email, I keep admin@domain.com

ServerName and ServerAlias — It needs to be the url you want, i.e., test.site

You can replace the project with the name of the application i.e., test .

Now you can save the file.

Now you need to tell apache that this conf file ready to be served, so you need to run this command:

sudo a2ensite test.site.conf

sudo service apache2 restart

dont forget to host the domain in host file

sudo nano /var/etc/hosts

update 127.0.1.1 yournewdomain.test (server alice)

a2ensite generally comes with apache installation. But you can install it externally as well.

And also you need to check if rewrites are enabled on the server. This is not the default setting, so you need to enable it.

You can enable the setting by running below command:

sudo a2enmod rewrite

sudo service apache2 restart

This rewrite module will help run the links on your server. By that I mean, when you don’t run above command, other than the homepage, no other link in your application will work and you will get this error.

Image for post

When you enable the rewrite module, it checks the .htaccess file and run all the links.

Now, there is just one step remaining, you need to add an entry in /etc/hosts file like below

127.0.0.1 test.site

This will tell the server, if any request comes from test.site you need to find its settings in conf file(if you find any) and run the appropriate application.

That’s it, now you can create a virtual host file of your own and run your applications like the way any server would do it.

Conclusion

Making a virtual host for you laravel applications can be really good for you in the long run. You can easily install your application on any apache server.

You now don’t need to run php artisan serve . Your application will directly be running and now you have some magic to show to your colleagues.

Happy learning….

https://medium.com/@bvipul/creating-virtual-host-on-linux-machine-for-your-laravel-applications-the-mighty-guide-70e2c17c0ab7