Chủ Nhật, 10 tháng 12, 2017

Laravel 5.5 Middleware Tutorial : How to Create Login with Multiple Level Access in laravel 5.5


Laravel 5.5 tutorial for beginners : This lessons will show you how to customize default Laravel Authentication using Middleware that can login with multiple level access.


Video tutorial Laravel 5.5 Middleware



Full source code

Create new Laravel Project using composer

composer create-project --prefer-dist laravel/laravel multiauth

User Migration

update user migration to add new field named with "admin"

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->boolean('admin')->default(0);
        });
    }

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

User Model

update the user model

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','admin',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Run Migration

php artisan migrate

Create Laravel Authentication

php artisan make:auth

Create New Middleware

php artisan make:middleware IsAdmin

Register middleware in app\Http\Kernel.php we can register the IsAdmin middleware

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareTrustProxies::class,
        AppHttpMiddlewareIsAdmin::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    ];
}

Routes (web.php)

<?php

Auth::routes();

Route::group(['middleware' => ['web','auth']], function(){
  Route::get('/', function () {
      return view('welcome');
  });

  Route::get('/home', function() {
    if (Auth::user()->admin == 0) {
      return view('home');
    } else {
      $users['users'] = AppUser::all();
      return view('adminhome', $users);
    }
  });
});

Create new Admin Page

If the users is "Admin", we will redirect to admin home pages, and if just the user will redirect into home pages

create new page in resources/view/ and named with "adminhome.blade.php"

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as ADMINISTRATOR</p>
                    </div>

                    <table class="table table-hover table-bordered">
                      <thead>
                        <tr>
                          <th width="5">No.</th>
                          <th>Member Name</th>
                          <th>Email</th>
                        </tr>
                      </thead>
                      <tbody>
                        @foreach ($users as $key => $value)
                          <tr>
                            <td>{{ $key+1 }}</td>
                            <td>{{ $value->name }}</td>
                            <td>{{ $value->email }}</td>
                          </tr>
                        @endforeach
                      </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as USERS</p>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

More Laravel Video Tutorial









See you next lessons and happy coding guys ...

Laravel 5.5 Middleware Tutorial : How to Create Login with Multiple Level Access in laravel 5.5


Laravel 5.5 tutorial for beginners : This lessons will show you how to customize default Laravel Authentication using Middleware that can login with multiple level access.


Video tutorial Laravel 5.5 Middleware



Full source code

Create new Laravel Project using composer

composer create-project --prefer-dist laravel/laravel multiauth

User Migration

update user migration to add new field named with "admin"

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->boolean('admin')->default(0);
        });
    }

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

User Model

update the user model

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','admin',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Run Migration

php artisan migrate

Create Laravel Authentication

php artisan make:auth

Create New Middleware

php artisan make:middleware IsAdmin

Register middleware in app\Http\Kernel.php we can register the IsAdmin middleware

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareTrustProxies::class,
        AppHttpMiddlewareIsAdmin::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    ];
}

Routes (web.php)

<?php

Auth::routes();

Route::group(['middleware' => ['web','auth']], function(){
  Route::get('/', function () {
      return view('welcome');
  });

  Route::get('/home', function() {
    if (Auth::user()->admin == 0) {
      return view('home');
    } else {
      $users['users'] = AppUser::all();
      return view('adminhome', $users);
    }
  });
});

Create new Admin Page

If the users is "Admin", we will redirect to admin home pages, and if just the user will redirect into home pages

create new page in resources/view/ and named with "adminhome.blade.php"

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as ADMINISTRATOR</p>
                    </div>

                    <table class="table table-hover table-bordered">
                      <thead>
                        <tr>
                          <th width="5">No.</th>
                          <th>Member Name</th>
                          <th>Email</th>
                        </tr>
                      </thead>
                      <tbody>
                        @foreach ($users as $key => $value)
                          <tr>
                            <td>{{ $key+1 }}</td>
                            <td>{{ $value->name }}</td>
                            <td>{{ $value->email }}</td>
                          </tr>
                        @endforeach
                      </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as USERS</p>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

More Laravel Video Tutorial









See you next lessons and happy coding guys ...

Laravel 5.5 Middleware Tutorial : How to Create Login with Multiple Level Access in laravel 5.5


Laravel 5.5 tutorial for beginners : This lessons will show you how to customize default Laravel Authentication using Middleware that can login with multiple level access.


Video tutorial Laravel 5.5 Middleware



Full source code

Create new Laravel Project using composer

composer create-project --prefer-dist laravel/laravel multiauth

User Migration

update user migration to add new field named with "admin"

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->boolean('admin')->default(0);
        });
    }

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

User Model

update the user model

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','admin',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Run Migration

php artisan migrate

Create Laravel Authentication

php artisan make:auth

Create New Middleware

php artisan make:middleware IsAdmin

Register middleware in app\Http\Kernel.php we can register the IsAdmin middleware

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareTrustProxies::class,
        AppHttpMiddlewareIsAdmin::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    ];
}

Routes (web.php)

<?php

Auth::routes();

Route::group(['middleware' => ['web','auth']], function(){
  Route::get('/', function () {
      return view('welcome');
  });

  Route::get('/home', function() {
    if (Auth::user()->admin == 0) {
      return view('home');
    } else {
      $users['users'] = AppUser::all();
      return view('adminhome', $users);
    }
  });
});

Create new Admin Page

If the users is "Admin", we will redirect to admin home pages, and if just the user will redirect into home pages

create new page in resources/view/ and named with "adminhome.blade.php"

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as ADMINISTRATOR</p>
                    </div>

                    <table class="table table-hover table-bordered">
                      <thead>
                        <tr>
                          <th width="5">No.</th>
                          <th>Member Name</th>
                          <th>Email</th>
                        </tr>
                      </thead>
                      <tbody>
                        @foreach ($users as $key => $value)
                          <tr>
                            <td>{{ $key+1 }}</td>
                            <td>{{ $value->name }}</td>
                            <td>{{ $value->email }}</td>
                          </tr>
                        @endforeach
                      </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    <div class="alert alert-success">
                        <p>You're logged in as USERS</p>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

More Laravel Video Tutorial









See you next lessons and happy coding guys ...

Thứ Bảy, 2 tháng 12, 2017

Laravel 5.5 AJAX Tutorial : Advanced CRUD Operation with Ajax JQuery in Laravel 5.5


Laravel 5.5 Ajax tutorial for beginners : This lesson will show you how to create Advanced complete CRUD operations, sort, search and pagination in laravel 5.5 with JQuery AJAX. at the previews lesson we have learn basic of CRUD Apps using laravel 5.5
  1. Laravel 5.5 & VUE.JS advanced CRUD Example
  2. Laravel 5.5 CRUD with resource controller
  3. Laravel 5.3 & Angular.JS CRUD Example

Video Tutorrial how to Create CRUD Example with Ajax



Step by step AJAX Crud example in Laravel 5.5

Create Laravel Project (Ajax Crud)

composer create-project --prefer-dist laravel/laravel ajaxcrud

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','description'];

Post Controller

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPost;
use IlluminateSupportFacadesValidator;

class PostController extends Controller
{
    public function index(Request $request)
    {
      $request->session()->put('search', $request
              ->has('search') ? $request->get('search') : ($request->session()
              ->has('search') ? $request->session()->get('search') : ''));

              $request->session()->put('field', $request
                      ->has('field') ? $request->get('field') : ($request->session()
                      ->has('field') ? $request->session()->get('field') : 'title'));

                      $request->session()->put('sort', $request
                              ->has('sort') ? $request->get('sort') : ($request->session()
                              ->has('sort') ? $request->session()->get('sort') : 'asc'));

      $posts = new Post();
            $posts = $posts->where('title', 'like', '%' . $request->session()->get('search') . '%')
                ->orderBy($request->session()->get('field'), $request->session()->get('sort'))
                ->paginate(5);
            if ($request->ajax()) {
              return view('posts.index', compact('posts'));
            } else {
              return view('posts.ajax', compact('posts'));
            }
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
        return view('posts.form');

        $rules = [
          'title' => 'required',
          'description' => 'required',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails())
        return response()->json([
          'fail' =>true,
          'errors' => $validator->errors()
        ]);

        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->save();

        return response()->json([
          'fail' => false,
          'redirect_url' => url('posts')
        ]);
    }

    public function show(Request $request, $id)
    {
        if($request->isMethod('get')) {
          return view('posts.detail',['post' => Post::find($id)]);
        }
    }

    public function update(Request $request, $id)
    {
      if ($request->isMethod('get'))
      return view('posts.form',['post' => Post::find($id)]);

      $rules = [
        'title' => 'required',
        'description' => 'required',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails())
      return response()->json([
        'fail' =>true,
        'errors' => $validator->errors()
      ]);

      $post = Post::find($id);
      $post->title = $request->title;
      $post->description = $request->description;
      $post->save();

      return response()->json([
        'fail' => false,
        'redirect_url' => url('posts')
      ]);
    }

    public function destroy($id)
    {
        Post::destroy($id);
        return redirect('posts');
    }
}

Routes

Route::group(['prefix' => 'posts'], function() {
  Route::get('/', 'PostController@index');
  Route::match(['get', 'post'], 'create', 'PostController@create');
  Route::match(['get', 'put'], 'update/{id}', 'PostController@update');
  Route::get('show/{id}', 'PostController@show');
  Route::delete('delete/{id}', 'PostController@destroy');
});

Views

in the Resources\Views folder, create new folder named with "posts", and in the posts folder create more file like this :
  1. master.blade.php
  2. index.blade.php
  3. ajax.blade.php
  4. detail.blade.php
  5. form.blade.php

Master.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Ajax Example</title>
@yield('head')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
@yield('css')
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar fixed-top bg-info">
    <a class="navbar-brand" href="/posts">Laravel Video Tutorial</a>
    @yield('nav')
</nav>

@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

@yield('js')
  </body>
</html>

Index.blade.php

<div class="container">

    <div class="row">
        <div class="col-sm-7">
          <h3>Laravel CRUD, Search, Sort - AJAX</h3>
        </div>
        <div class="col-sm-5">
          <div class="pull-right">
            <div class="input-group">
                <input class="form-control" id="search"
                       value="{{ request()->session()->get('search') }}"
                       onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('posts')}}?search='+this.value)"
                       placeholder="Search Title" name="search"
                       type="text" id="search"/>
                <div class="input-group-btn">
                    <button type="submit" class="btn btn-primary"
                            onclick="ajaxLoad('{{url('posts')}}?search='+$('#search').val())">
                            <i class="fa fa-search" aria-hidden="true"></i>
                    </button>
                </div>
            </div>

          </div>
        </div>
    </div>
    <table class="table">
        <thead>
        <tr>

            <th width="60px">No</th>
            <th><a href="javascript:ajaxLoad('{{url('posts?field=title&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">Post Title</a>
                {{request()->session()->get('field')=='title'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=description&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Description
                </a>
                {{request()->session()->get('field')=='description'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=created_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Created At
                </a>
                {{request()->session()->get('field')=='created_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts?field=updated_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                Update At
              </a>
              {{request()->session()->get('field')=='updated_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>
            <th width="160px" style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts/create')}}')"
                 class="btn btn-primary btn-xs"> <i class="fa fa-plus" aria-hidden="true"></i> New Post</a>
            </th>
        </tr>
        </thead>
        <tbody>
        @php
            $i=1;
        @endphp
        @foreach ($posts as $post)
          <tr>
            <th>{{$i++}}</th>
            <td>{{ $post->title }}</td>
            <td >{{ $post->description }}</td>
            <td>{{ $post->created_at }}</td>
            <td>{{ $post->updated_at }}</td>
            <td>
              <a class="btn btn-info btn-xs" title="Show"
                 href="javascript:ajaxLoad('{{url('posts/show/'.$post->id)}}')">
                  Show</a>
                <a class="btn btn-warning btn-xs" title="Edit"
                   href="javascript:ajaxLoad('{{url('posts/update/'.$post->id)}}')">
                    Edit</a>
                <input type="hidden" name="_method" value="delete"/>
                <a class="btn btn-danger btn-xs" title="Delete"
                   href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('{{url('posts/delete/'.$post->id)}}','{{csrf_token()}}')">
                    Delete
                </a>
            </td>
        </tr>
        @endforeach

        </tbody>
    </table>

        <ul class="pagination">
            {{ $posts->links() }}
        </ul>
</div>

Form.blade.php

<div class="container">
    <div class="col-md-8 offset-md-2">
        <h1>{{isset($post)?'Edit':'New'}} Post</h1>
        <hr/>
        @if(isset($post))
            {!! Form::model($post,['method'=>'put','id'=>'frm']) !!}
        @else
            {!! Form::open(['id'=>'frm']) !!}
        @endif
        <div class="form-group row required">
            {!! Form::label("title","Title",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::text("title",null,["class"=>"form-control".($errors->has('title')?" is-invalid":""),"autofocus",'placeholder'=>'Title']) !!}
                <span id="error-title" class="invalid-feedback"></span>
            </div>
        </div>

        <div class="form-group row required">
            {!! Form::label("description","Description",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::textarea("description",null,["class"=>"form-control".($errors->has('description')?" is-invalid":""),'placeholder'=>'Description']) !!}
                <span id="error-description" class="invalid-feedback"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-md-3 col-lg-2"></div>
            <div class="col-md-4">
                <a href="javascript:ajaxLoad('{{url('posts')}}')" class="btn btn-danger btn-xs">
                    Back</a>
                {!! Form::button("Save",["type" => "submit","class"=>"btn btn-primary btn-xs"])!!}
            </div>
        </div>
        {!! Form::close() !!}
    </div>
</div>

Detail.blade.php

<div class="container">
  <div class="col-md-8 offset-md2">
    <h2>Show Post</h2>
    <hr>
    <div class="form-group">
      <h2>{{ $post->title }}</h2>
    </div>

    <div class="form-group">
      <h2>{{ $post->description }}</h2>
    </div>

    <a class="btn btn-xs btn-danger" href="javascript:ajaxLoad('{{ url('posts') }}')">Back</a>
  </div>
</div>

Ajax.blade.php

@extends('posts.master')

@section('css')
  <style>
      .loading {
          background: lightgrey;
          padding: 15px;
          position: fixed;
          border-radius: 4px;
          left: 50%;
          top: 50%;
          text-align: center;
          margin: -40px 0 0 -50px;
          z-index: 2000;
          display: none;
      }

      .form-group.required label:after {
          content: " *";
          color: red;
          font-weight: bold;
      }
  </style>
@endsection
@section('content')
  <div id="content">
    @include('posts.index')
  </div>
  <div class="loading">
    <i class="fa fa-refresh fa-spin fa-2x fa-tw"></i>
    <br>
    <span>Loading</span>
  </div>
@endsection

@section('js')
  <script src="{{ asset('js/ajaxcrud.js') }}"></script>
@endsection

Create new Js File

in the Public\js create new file and named it with "ajaxcrud.js"

$(document).on('click', 'a.page-link', function (event) {
    event.preventDefault();
    ajaxLoad($(this).attr('href'));
});

$(document).on('submit', 'form#frm', function (event) {
    event.preventDefault();
    var form = $(this);
    var data = new FormData($(this)[0]);
    var url = form.attr("action");
    $.ajax({
        type: form.attr('method'),
        url: url,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            $('.is-invalid').removeClass('is-invalid');
            if (data.fail) {
                for (control in data.errors) {
                    $('#' + control).addClass('is-invalid');
                    $('#error-' + control).html(data.errors[control]);
                }
            } else {
                ajaxLoad(data.redirect_url);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("Error: " + errorThrown);
        }
    });
    return false;
});

function ajaxLoad(filename, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: "GET",
        url: filename,
        contentType: false,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function ajaxDelete(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'DELETE', _token: token},
        url: filename,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

More Laravel Video Tutorial








See you next lessons and happy coding guys ...

Laravel 5.5 AJAX Tutorial : Advanced CRUD Operation with Ajax JQuery in Laravel 5.5


Laravel 5.5 Ajax tutorial for beginners : This lesson will show you how to create Advanced complete CRUD operations, sort, search and pagination in laravel 5.5 with JQuery AJAX. at the previews lesson we have learn basic of CRUD Apps using laravel 5.5
  1. Laravel 5.5 & VUE.JS advanced CRUD Example
  2. Laravel 5.5 CRUD with resource controller
  3. Laravel 5.3 & Angular.JS CRUD Example

Video Tutorrial how to Create CRUD Example with Ajax



Step by step AJAX Crud example in Laravel 5.5

Create Laravel Project (Ajax Crud)

composer create-project --prefer-dist laravel/laravel ajaxcrud

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','description'];

Post Controller

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPost;
use IlluminateSupportFacadesValidator;

class PostController extends Controller
{
    public function index(Request $request)
    {
      $request->session()->put('search', $request
              ->has('search') ? $request->get('search') : ($request->session()
              ->has('search') ? $request->session()->get('search') : ''));

              $request->session()->put('field', $request
                      ->has('field') ? $request->get('field') : ($request->session()
                      ->has('field') ? $request->session()->get('field') : 'title'));

                      $request->session()->put('sort', $request
                              ->has('sort') ? $request->get('sort') : ($request->session()
                              ->has('sort') ? $request->session()->get('sort') : 'asc'));

      $posts = new Post();
            $posts = $posts->where('title', 'like', '%' . $request->session()->get('search') . '%')
                ->orderBy($request->session()->get('field'), $request->session()->get('sort'))
                ->paginate(5);
            if ($request->ajax()) {
              return view('posts.index', compact('posts'));
            } else {
              return view('posts.ajax', compact('posts'));
            }
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
        return view('posts.form');

        $rules = [
          'title' => 'required',
          'description' => 'required',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails())
        return response()->json([
          'fail' =>true,
          'errors' => $validator->errors()
        ]);

        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->save();

        return response()->json([
          'fail' => false,
          'redirect_url' => url('posts')
        ]);
    }

    public function show(Request $request, $id)
    {
        if($request->isMethod('get')) {
          return view('posts.detail',['post' => Post::find($id)]);
        }
    }

    public function update(Request $request, $id)
    {
      if ($request->isMethod('get'))
      return view('posts.form',['post' => Post::find($id)]);

      $rules = [
        'title' => 'required',
        'description' => 'required',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails())
      return response()->json([
        'fail' =>true,
        'errors' => $validator->errors()
      ]);

      $post = Post::find($id);
      $post->title = $request->title;
      $post->description = $request->description;
      $post->save();

      return response()->json([
        'fail' => false,
        'redirect_url' => url('posts')
      ]);
    }

    public function destroy($id)
    {
        Post::destroy($id);
        return redirect('posts');
    }
}

Routes

Route::group(['prefix' => 'posts'], function() {
  Route::get('/', 'PostController@index');
  Route::match(['get', 'post'], 'create', 'PostController@create');
  Route::match(['get', 'put'], 'update/{id}', 'PostController@update');
  Route::get('show/{id}', 'PostController@show');
  Route::delete('delete/{id}', 'PostController@destroy');
});

Views

in the Resources\Views folder, create new folder named with "posts", and in the posts folder create more file like this :
  1. master.blade.php
  2. index.blade.php
  3. ajax.blade.php
  4. detail.blade.php
  5. form.blade.php

Master.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Ajax Example</title>
@yield('head')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
@yield('css')
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar fixed-top bg-info">
    <a class="navbar-brand" href="/posts">Laravel Video Tutorial</a>
    @yield('nav')
</nav>

@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

@yield('js')
  </body>
</html>

Index.blade.php

<div class="container">

    <div class="row">
        <div class="col-sm-7">
          <h3>Laravel CRUD, Search, Sort - AJAX</h3>
        </div>
        <div class="col-sm-5">
          <div class="pull-right">
            <div class="input-group">
                <input class="form-control" id="search"
                       value="{{ request()->session()->get('search') }}"
                       onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('posts')}}?search='+this.value)"
                       placeholder="Search Title" name="search"
                       type="text" id="search"/>
                <div class="input-group-btn">
                    <button type="submit" class="btn btn-primary"
                            onclick="ajaxLoad('{{url('posts')}}?search='+$('#search').val())">
                            <i class="fa fa-search" aria-hidden="true"></i>
                    </button>
                </div>
            </div>

          </div>
        </div>
    </div>
    <table class="table">
        <thead>
        <tr>

            <th width="60px">No</th>
            <th><a href="javascript:ajaxLoad('{{url('posts?field=title&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">Post Title</a>
                {{request()->session()->get('field')=='title'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=description&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Description
                </a>
                {{request()->session()->get('field')=='description'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=created_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Created At
                </a>
                {{request()->session()->get('field')=='created_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts?field=updated_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                Update At
              </a>
              {{request()->session()->get('field')=='updated_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>
            <th width="160px" style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts/create')}}')"
                 class="btn btn-primary btn-xs"> <i class="fa fa-plus" aria-hidden="true"></i> New Post</a>
            </th>
        </tr>
        </thead>
        <tbody>
        @php
            $i=1;
        @endphp
        @foreach ($posts as $post)
          <tr>
            <th>{{$i++}}</th>
            <td>{{ $post->title }}</td>
            <td >{{ $post->description }}</td>
            <td>{{ $post->created_at }}</td>
            <td>{{ $post->updated_at }}</td>
            <td>
              <a class="btn btn-info btn-xs" title="Show"
                 href="javascript:ajaxLoad('{{url('posts/show/'.$post->id)}}')">
                  Show</a>
                <a class="btn btn-warning btn-xs" title="Edit"
                   href="javascript:ajaxLoad('{{url('posts/update/'.$post->id)}}')">
                    Edit</a>
                <input type="hidden" name="_method" value="delete"/>
                <a class="btn btn-danger btn-xs" title="Delete"
                   href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('{{url('posts/delete/'.$post->id)}}','{{csrf_token()}}')">
                    Delete
                </a>
            </td>
        </tr>
        @endforeach

        </tbody>
    </table>

        <ul class="pagination">
            {{ $posts->links() }}
        </ul>
</div>

Form.blade.php

<div class="container">
    <div class="col-md-8 offset-md-2">
        <h1>{{isset($post)?'Edit':'New'}} Post</h1>
        <hr/>
        @if(isset($post))
            {!! Form::model($post,['method'=>'put','id'=>'frm']) !!}
        @else
            {!! Form::open(['id'=>'frm']) !!}
        @endif
        <div class="form-group row required">
            {!! Form::label("title","Title",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::text("title",null,["class"=>"form-control".($errors->has('title')?" is-invalid":""),"autofocus",'placeholder'=>'Title']) !!}
                <span id="error-title" class="invalid-feedback"></span>
            </div>
        </div>

        <div class="form-group row required">
            {!! Form::label("description","Description",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::textarea("description",null,["class"=>"form-control".($errors->has('description')?" is-invalid":""),'placeholder'=>'Description']) !!}
                <span id="error-description" class="invalid-feedback"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-md-3 col-lg-2"></div>
            <div class="col-md-4">
                <a href="javascript:ajaxLoad('{{url('posts')}}')" class="btn btn-danger btn-xs">
                    Back</a>
                {!! Form::button("Save",["type" => "submit","class"=>"btn btn-primary btn-xs"])!!}
            </div>
        </div>
        {!! Form::close() !!}
    </div>
</div>

Detail.blade.php

<div class="container">
  <div class="col-md-8 offset-md2">
    <h2>Show Post</h2>
    <hr>
    <div class="form-group">
      <h2>{{ $post->title }}</h2>
    </div>

    <div class="form-group">
      <h2>{{ $post->description }}</h2>
    </div>

    <a class="btn btn-xs btn-danger" href="javascript:ajaxLoad('{{ url('posts') }}')">Back</a>
  </div>
</div>

Ajax.blade.php

@extends('posts.master')

@section('css')
  <style>
      .loading {
          background: lightgrey;
          padding: 15px;
          position: fixed;
          border-radius: 4px;
          left: 50%;
          top: 50%;
          text-align: center;
          margin: -40px 0 0 -50px;
          z-index: 2000;
          display: none;
      }

      .form-group.required label:after {
          content: " *";
          color: red;
          font-weight: bold;
      }
  </style>
@endsection
@section('content')
  <div id="content">
    @include('posts.index')
  </div>
  <div class="loading">
    <i class="fa fa-refresh fa-spin fa-2x fa-tw"></i>
    <br>
    <span>Loading</span>
  </div>
@endsection

@section('js')
  <script src="{{ asset('js/ajaxcrud.js') }}"></script>
@endsection

Create new Js File

in the Public\js create new file and named it with "ajaxcrud.js"

$(document).on('click', 'a.page-link', function (event) {
    event.preventDefault();
    ajaxLoad($(this).attr('href'));
});

$(document).on('submit', 'form#frm', function (event) {
    event.preventDefault();
    var form = $(this);
    var data = new FormData($(this)[0]);
    var url = form.attr("action");
    $.ajax({
        type: form.attr('method'),
        url: url,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            $('.is-invalid').removeClass('is-invalid');
            if (data.fail) {
                for (control in data.errors) {
                    $('#' + control).addClass('is-invalid');
                    $('#error-' + control).html(data.errors[control]);
                }
            } else {
                ajaxLoad(data.redirect_url);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("Error: " + errorThrown);
        }
    });
    return false;
});

function ajaxLoad(filename, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: "GET",
        url: filename,
        contentType: false,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function ajaxDelete(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'DELETE', _token: token},
        url: filename,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

More Laravel Video Tutorial








See you next lessons and happy coding guys ...

Laravel 5.5 AJAX Tutorial : Advanced CRUD Operation with Ajax JQuery in Laravel 5.5


Laravel 5.5 Ajax tutorial for beginners : This lesson will show you how to create Advanced complete CRUD operations, sort, search and pagination in laravel 5.5 with JQuery AJAX. at the previews lesson we have learn basic of CRUD Apps using laravel 5.5
  1. Laravel 5.5 & VUE.JS advanced CRUD Example
  2. Laravel 5.5 CRUD with resource controller
  3. Laravel 5.3 & Angular.JS CRUD Example

Video Tutorrial how to Create CRUD Example with Ajax



Step by step AJAX Crud example in Laravel 5.5

Create Laravel Project (Ajax Crud)

composer create-project --prefer-dist laravel/laravel ajaxcrud

Create new Migration

php artisan make:migration create_posts_table

Post Migration

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });

Create new Model and new Controller

php artisan make:model Post

php artisan make:controller PostController --resource

Post Model

protected $table = 'posts';
protected $fillable = ['title','description'];

Post Controller

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPost;
use IlluminateSupportFacadesValidator;

class PostController extends Controller
{
    public function index(Request $request)
    {
      $request->session()->put('search', $request
              ->has('search') ? $request->get('search') : ($request->session()
              ->has('search') ? $request->session()->get('search') : ''));

              $request->session()->put('field', $request
                      ->has('field') ? $request->get('field') : ($request->session()
                      ->has('field') ? $request->session()->get('field') : 'title'));

                      $request->session()->put('sort', $request
                              ->has('sort') ? $request->get('sort') : ($request->session()
                              ->has('sort') ? $request->session()->get('sort') : 'asc'));

      $posts = new Post();
            $posts = $posts->where('title', 'like', '%' . $request->session()->get('search') . '%')
                ->orderBy($request->session()->get('field'), $request->session()->get('sort'))
                ->paginate(5);
            if ($request->ajax()) {
              return view('posts.index', compact('posts'));
            } else {
              return view('posts.ajax', compact('posts'));
            }
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
        return view('posts.form');

        $rules = [
          'title' => 'required',
          'description' => 'required',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails())
        return response()->json([
          'fail' =>true,
          'errors' => $validator->errors()
        ]);

        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->save();

        return response()->json([
          'fail' => false,
          'redirect_url' => url('posts')
        ]);
    }

    public function show(Request $request, $id)
    {
        if($request->isMethod('get')) {
          return view('posts.detail',['post' => Post::find($id)]);
        }
    }

    public function update(Request $request, $id)
    {
      if ($request->isMethod('get'))
      return view('posts.form',['post' => Post::find($id)]);

      $rules = [
        'title' => 'required',
        'description' => 'required',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails())
      return response()->json([
        'fail' =>true,
        'errors' => $validator->errors()
      ]);

      $post = Post::find($id);
      $post->title = $request->title;
      $post->description = $request->description;
      $post->save();

      return response()->json([
        'fail' => false,
        'redirect_url' => url('posts')
      ]);
    }

    public function destroy($id)
    {
        Post::destroy($id);
        return redirect('posts');
    }
}

Routes

Route::group(['prefix' => 'posts'], function() {
  Route::get('/', 'PostController@index');
  Route::match(['get', 'post'], 'create', 'PostController@create');
  Route::match(['get', 'put'], 'update/{id}', 'PostController@update');
  Route::get('show/{id}', 'PostController@show');
  Route::delete('delete/{id}', 'PostController@destroy');
});

Views

in the Resources\Views folder, create new folder named with "posts", and in the posts folder create more file like this :
  1. master.blade.php
  2. index.blade.php
  3. ajax.blade.php
  4. detail.blade.php
  5. form.blade.php

Master.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Ajax Example</title>
@yield('head')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
@yield('css')
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar fixed-top bg-info">
    <a class="navbar-brand" href="/posts">Laravel Video Tutorial</a>
    @yield('nav')
</nav>

@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

@yield('js')
  </body>
</html>

Index.blade.php

<div class="container">

    <div class="row">
        <div class="col-sm-7">
          <h3>Laravel CRUD, Search, Sort - AJAX</h3>
        </div>
        <div class="col-sm-5">
          <div class="pull-right">
            <div class="input-group">
                <input class="form-control" id="search"
                       value="{{ request()->session()->get('search') }}"
                       onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('posts')}}?search='+this.value)"
                       placeholder="Search Title" name="search"
                       type="text" id="search"/>
                <div class="input-group-btn">
                    <button type="submit" class="btn btn-primary"
                            onclick="ajaxLoad('{{url('posts')}}?search='+$('#search').val())">
                            <i class="fa fa-search" aria-hidden="true"></i>
                    </button>
                </div>
            </div>

          </div>
        </div>
    </div>
    <table class="table">
        <thead>
        <tr>

            <th width="60px">No</th>
            <th><a href="javascript:ajaxLoad('{{url('posts?field=title&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">Post Title</a>
                {{request()->session()->get('field')=='title'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=description&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Description
                </a>
                {{request()->session()->get('field')=='description'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
                <a href="javascript:ajaxLoad('{{url('posts?field=created_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                    Created At
                </a>
                {{request()->session()->get('field')=='created_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>

            <th style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts?field=updated_at&sort='.(request()->session()->get('sort')=='asc'?'desc':'asc'))}}')">
                Update At
              </a>
              {{request()->session()->get('field')=='updated_at'?(request()->session()->get('sort')=='asc'?'&#9652;':'&#9662;'):''}}
            </th>
            <th width="160px" style="vertical-align: middle">
              <a href="javascript:ajaxLoad('{{url('posts/create')}}')"
                 class="btn btn-primary btn-xs"> <i class="fa fa-plus" aria-hidden="true"></i> New Post</a>
            </th>
        </tr>
        </thead>
        <tbody>
        @php
            $i=1;
        @endphp
        @foreach ($posts as $post)
          <tr>
            <th>{{$i++}}</th>
            <td>{{ $post->title }}</td>
            <td >{{ $post->description }}</td>
            <td>{{ $post->created_at }}</td>
            <td>{{ $post->updated_at }}</td>
            <td>
              <a class="btn btn-info btn-xs" title="Show"
                 href="javascript:ajaxLoad('{{url('posts/show/'.$post->id)}}')">
                  Show</a>
                <a class="btn btn-warning btn-xs" title="Edit"
                   href="javascript:ajaxLoad('{{url('posts/update/'.$post->id)}}')">
                    Edit</a>
                <input type="hidden" name="_method" value="delete"/>
                <a class="btn btn-danger btn-xs" title="Delete"
                   href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('{{url('posts/delete/'.$post->id)}}','{{csrf_token()}}')">
                    Delete
                </a>
            </td>
        </tr>
        @endforeach

        </tbody>
    </table>

        <ul class="pagination">
            {{ $posts->links() }}
        </ul>
</div>

Form.blade.php

<div class="container">
    <div class="col-md-8 offset-md-2">
        <h1>{{isset($post)?'Edit':'New'}} Post</h1>
        <hr/>
        @if(isset($post))
            {!! Form::model($post,['method'=>'put','id'=>'frm']) !!}
        @else
            {!! Form::open(['id'=>'frm']) !!}
        @endif
        <div class="form-group row required">
            {!! Form::label("title","Title",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::text("title",null,["class"=>"form-control".($errors->has('title')?" is-invalid":""),"autofocus",'placeholder'=>'Title']) !!}
                <span id="error-title" class="invalid-feedback"></span>
            </div>
        </div>

        <div class="form-group row required">
            {!! Form::label("description","Description",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
            <div class="col-md-8">
                {!! Form::textarea("description",null,["class"=>"form-control".($errors->has('description')?" is-invalid":""),'placeholder'=>'Description']) !!}
                <span id="error-description" class="invalid-feedback"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-md-3 col-lg-2"></div>
            <div class="col-md-4">
                <a href="javascript:ajaxLoad('{{url('posts')}}')" class="btn btn-danger btn-xs">
                    Back</a>
                {!! Form::button("Save",["type" => "submit","class"=>"btn btn-primary btn-xs"])!!}
            </div>
        </div>
        {!! Form::close() !!}
    </div>
</div>

Detail.blade.php

<div class="container">
  <div class="col-md-8 offset-md2">
    <h2>Show Post</h2>
    <hr>
    <div class="form-group">
      <h2>{{ $post->title }}</h2>
    </div>

    <div class="form-group">
      <h2>{{ $post->description }}</h2>
    </div>

    <a class="btn btn-xs btn-danger" href="javascript:ajaxLoad('{{ url('posts') }}')">Back</a>
  </div>
</div>

Ajax.blade.php

@extends('posts.master')

@section('css')
  <style>
      .loading {
          background: lightgrey;
          padding: 15px;
          position: fixed;
          border-radius: 4px;
          left: 50%;
          top: 50%;
          text-align: center;
          margin: -40px 0 0 -50px;
          z-index: 2000;
          display: none;
      }

      .form-group.required label:after {
          content: " *";
          color: red;
          font-weight: bold;
      }
  </style>
@endsection
@section('content')
  <div id="content">
    @include('posts.index')
  </div>
  <div class="loading">
    <i class="fa fa-refresh fa-spin fa-2x fa-tw"></i>
    <br>
    <span>Loading</span>
  </div>
@endsection

@section('js')
  <script src="{{ asset('js/ajaxcrud.js') }}"></script>
@endsection

Create new Js File

in the Public\js create new file and named it with "ajaxcrud.js"

$(document).on('click', 'a.page-link', function (event) {
    event.preventDefault();
    ajaxLoad($(this).attr('href'));
});

$(document).on('submit', 'form#frm', function (event) {
    event.preventDefault();
    var form = $(this);
    var data = new FormData($(this)[0]);
    var url = form.attr("action");
    $.ajax({
        type: form.attr('method'),
        url: url,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            $('.is-invalid').removeClass('is-invalid');
            if (data.fail) {
                for (control in data.errors) {
                    $('#' + control).addClass('is-invalid');
                    $('#error-' + control).html(data.errors[control]);
                }
            } else {
                ajaxLoad(data.redirect_url);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("Error: " + errorThrown);
        }
    });
    return false;
});

function ajaxLoad(filename, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: "GET",
        url: filename,
        contentType: false,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function ajaxDelete(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'DELETE', _token: token},
        url: filename,
        success: function (data) {
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

More Laravel Video Tutorial








See you next lessons and happy coding guys ...

Thứ Ba, 28 tháng 11, 2017

Laravel 5.5 Ajax Tutorial : Select Selected Value a Dropdown with Dynamic Dropdown


Laravel 5.5 Ajax tutorial : This tutorial will show you how to select Selected Value from a Dynamic Dropdown in laravel 5.5 with JQuery Ajax step by step.


Video Tutorial Select Value Dropdown



Full Source Code

Create new Laravel Project

composer create-project --prefer-dist laravel/laravel indonesia

Create new Controller

php artisan make:controller CountryController

CountryController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesInput;

use AppProvinces;
use AppRegencies;
use AppDistricts;
use AppVillages;

class CountryController extends Controller
{
    public function provinces(){
      $provinces = Provinces::all();
      return view('indonesia', compact('provinces'));
    }

    public function regencies(){
      $provinces_id = Input::get('province_id');
      $regencies = Regencies::where('province_id', '=', $provinces_id)->get();
      return response()->json($regencies);
    }

    public function districts(){
      $regencies_id = Input::get('regencies_id');
      $districts = Districts::where('regency_id', '=', $regencies_id)->get();
      return response()->json($districts);
    }

    public function villages(){
      $districts_id = Input::get('districts_id');
      $villages = Villages::where('district_id', '=', $districts_id)->get();
      return response()->json($villages);
    }
}

Create new Model

php artisan make:model Provinces
php artisan make:model Regencies
php artisan make:model Districts
php artisan make:model Villages

Provinces.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Provinces extends Model
{
    protected $table = 'provinces';
}

Regencies.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Regencies extends Model
{
    protected $table = 'regencies';
}

Districts.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Districts extends Model
{
    protected $table = 'districts';
}

Villages.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Villages extends Model
{
    protected $table = 'villages';
}

Add new Route

Route::get('/indonesia','CountryController@provinces');

Route::get('/json-regencies','CountryController@regencies');

Route::get('/json-districts', 'CountryController@districts');

Route::get('/json-village', 'CountryController@villages');

Setup Connection to Database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=indonesia
DB_USERNAME=root
DB_PASSWORD=null

Create New View

Indonesia.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Indonesia</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
      <div class="col-lg-4">
        <h2>Laravel 5.5 JQuery Ajax Example</h2>
        {{ Form::open() }}
          <div class="form-group">
            <label for="">Your Provinces</label>
            <select class="form-control" name="provinces" id="provinces">
              <option value="0" disable="true" selected="true">=== Select Provinces ===</option>
                @foreach ($provinces as $key => $value)
                  <option value="{{$value->id}}">{{ $value->name }}</option>
                @endforeach
            </select>
          </div>

          <div class="form-group">
            <label for="">Your Regencies</label>
            <select class="form-control" name="regencies" id="regencies">
              <option value="0" disable="true" selected="true">=== Select Regencies ===</option>
            </select>
          </div>

          <div class="form-group">
            <label for="">Your Districts</label>
            <select class="form-control" name="districts" id="districts">
              <option value="0" disable="true" selected="true">=== Select Districts ===</option>
            </select>
          </div>

          <div class="form-group">
            <label for="">Your Villages</label>
            <select class="form-control" name="villages" id="villages">
              <option value="0" disable="true" selected="true">=== Select Villages ===</option>
            </select>
          </div>

        {{ Form::close() }}
      </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script type="text/javascript">
      $('#provinces').on('change', function(e){
        console.log(e);
        var province_id = e.target.value;
        $.get('/json-regencies?province_id=' + province_id,function(data) {
          console.log(data);
          $('#regencies').empty();
          $('#regencies').append('<option value="0" disable="true" selected="true">=== Select Regencies ===</option>');

          $('#districts').empty();
          $('#districts').append('<option value="0" disable="true" selected="true">=== Select Districts ===</option>');

          $('#villages').empty();
          $('#villages').append('<option value="0" disable="true" selected="true">=== Select Villages ===</option>');

          $.each(data, function(index, regenciesObj){
            $('#regencies').append('<option value="'+ regenciesObj.id +'">'+ regenciesObj.name +'</option>');
          })
        });
      });

      $('#regencies').on('change', function(e){
        console.log(e);
        var regencies_id = e.target.value;
        $.get('/json-districts?regencies_id=' + regencies_id,function(data) {
          console.log(data);
          $('#districts').empty();
          $('#districts').append('<option value="0" disable="true" selected="true">=== Select Districts ===</option>');

          $.each(data, function(index, districtsObj){
            $('#districts').append('<option value="'+ districtsObj.id +'">'+ districtsObj.name +'</option>');
          })
        });
      });

      $('#districts').on('change', function(e){
        console.log(e);
        var districts_id = e.target.value;
        $.get('/json-village?districts_id=' + districts_id,function(data) {
          console.log(data);
          $('#villages').empty();
          $('#villages').append('<option value="0" disable="true" selected="true">=== Select Villages ===</option>');

          $.each(data, function(index, villagesObj){
            $('#villages').append('<option value="'+ villagesObj.id +'">'+ villagesObj.name +'</option>');
          })
        });
      });


    </script>

  </body>
</html>


Download Database Project from this link https://raw.githubusercontent.com/edwardsamuel/Wilayah-Administratif-Indonesia/master/mysql/indonesia.sql

More Laravel Video Tutorial











Happy coding guys ...