Laravel ajax datatables tutorial

Laravel ajax datatables tutorial

https://ift.tt/2W0mggE


jQuery datatable is very popular for listing data in web application with various interactive features like live-searching, pagination, sorting and more. If you want to use jQuery datatables in your laravel application then here I’m going to show you how to use jQuery-datatables in laravel and how to work for laravel datatables ajax, laravel datatables server-side, datatables customization and more. In this tutorial post, I will use a popular laravel package for datatables named yajra/laravel-datatables for making our task easier. Let’s start.

 

Laravel yajra/laravel-datatables ajax steps

  1. Install the yajra/laravel-datatables package.
  2. Define routes.
  3. Make a controller for datatable.
  4. Make view and add Js libraries.
  5. Code for jQuery datatables.

 

1. Install the yajra/laravel-datatables package

First, we have to Install the yajra/laravel-datatables package by composer command.

composer require yajra/laravel-datatables-oracle:"~9.0"

 

2. Define routes

Now let’s define these two routes in the web.phpp route file. You can change the route endpoints according to your application.

Route::get('api/customers','CustomerController@data');
Route::get('customers','CustomerController@index');

 

3. Make a controller for datatable

Now make a controller to handle the view and feed data to our jQuery datatables. Run the artisan command below to make a controller.

php artisan make:controller CustomerController

Do code in the controller:

<?php namespace App\Http\Controllers;

use App\Customer;

class CustomerController extends Controller
{

    public function index()
    {
        return view('customers');
    }

    public function data()
    {
        $customers = Customer::all();
        return datatables()->of($customers)->toJson();
    }
}

Note: Look from the index method we are just returning a simple view customers which we’ll create later and from data method we are returning JSON data for feed it to jQuery datatables. Here we have just used datatables()->of($data)->toJson(); you can find more option from yajra/laravel-datatables documentation.

 

With help of the datatables()->of() method from the yajra/larave-datatables package, we will get the formated JSON in example.com/api/customers endpoint look like below. So we don’t need to do anything about data formation.

{
  "draw": 0,
  "recordsTotal": 20,
  "recordsFiltered": 20,
  "data": [
    {
      "id": 1,
      "name": "Kenya",
      "email": "Cheyenne.Nolan94@hotmail.com",
      "phone": "910-845479",
      "dob": "1982-10-22"
    },
    {
      "id": 2,
      "name": "Madisen",
      "email": "Soledad.Schumm23@yahoo.com",
      "phone": "910-450685",
      "dob": "1984-09-19"
    },

    ...
    ...
}

 

4. Make view and add Js libraries.

Make a view customers.blade.php inside resources/views directory and add js dependencies. jQuery datatables need the jQuery library. So we have to add it first then datatables CSS and Js file. Let’s do that.

Note: You can add CSS, Js library files inside your master layout file, here I’m adding these into customers.blade.php file for tutorial purpose.

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <h3>Customers</h3>
                <hr>
                <table id="customers" class="table table-bordered table-condensed table-striped" >
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>DOB</th>
                    </tr>
                    </thead>

                </table>


                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
                <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet">
                <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

                <!-- our script will be here -->
            </div>
        </div>
    </div>
@endsection 

 

5. Code for jQuery datatables

Now add the code given below at the end of customers.blade.php file for showing data in interactive jQuery datatable. For laravel datatables ajax, set the ajax value of our API endpoint for fetching the customers data and set value true for yajra/laravel-datatables server-side.

$(document).ready(function() {
    $.noConflict();
    
    $('#customers').DataTable({
        ajax: '',
        serverSide: true,
        processing: true,
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'phone', name: 'phone'},
            {data: 'dob', name: 'dob'}
        ]
    });
})

 

Output Laravel-Datatable

Browse example.com/customers and you will get the result looks like given output screenshot.

laravel-yajra-datatables.png

 

Laravel Datatables customization

 

Add a custom column to the datatables

To add a custom column into yajra/laravel-datatables API data use addColumn('coumn_name',callback) method. Suppose we need another column for action like edit, delete button.

public function data()
{
    $customers = Customer::all();
    return datatables()->of($customers)
        ->addColumn('action', function ($row) {
            $html = '<a href="#" class="btn btn-xs btn-secondary">Edit</a> ';
            $html .= '<button data-rowid="'.$row->id.'" class="btn btn-xs btn-danger">Del</button>';
            return $html;
        })->toJson();
}

In HTML markup table add the column

<th>Action</th>

Add the column in script’s columns array.

{data: 'action', name: 'action'},

datatables-addcolumn.png

 

Disable searching & sorting for a specific column

To disable searching and sorting for specific column add orderable and searchable false.

{data: 'action', name: 'action', orderable: false, searchable: false},

 

Add custom ajax loader image to datatables

To add custom ajax loader image to jQuery datatables add the image with oLanguage into the script.

oLanguage: {
    sProcessing: "<img src='image_url_here'>"
},

 

Datatables Pre-sorted data with a specific column

To show datatables data with pre-sorted with a specific column, add the aaSorting property.

aaSorting: [[0, "desc"]],

Note: Here 0 refers to the first column of the datatables.

 

Hope this tutorial post help you to integrate jQuery datatables with yajra/laravel-datatables package. If you find this post helpful to you then please share this post with others so that they will get helped.

programming

via Laravel News Links https://ift.tt/2dvygAJ

December 10, 2020 at 08:06PM

Huge Star Wars Updates: Andor Teaser, Obi-Wan Timeline, Lando Show, and The Acolyte

Huge Star Wars Updates: Andor Teaser, Obi-Wan Timeline, Lando Show, and The Acolyte

https://ift.tt/3gHlLSb


Ewan McGregor is suiting up as Obi-Wan very soon.
Photo: Lucasfilm

Star Wars and Disney+ will continue to get cozy even when The Mandalorain isn’t around. At Disney’s 2020 Investor’s Day event, significant updates were given on the other Star Wars official shows we knew were coming to Disney+.

First up, Andor will be released in 2022 and began filming two weeks ago. Here’s a sizzle reel:

The Obi-Wan Kenobi show takes place ten years after Revenge of the Sith and will bring back Hayden Christensen as Darth Vader. Footage was shown, even though it won’t start shooting until next year, but it wasn’t online. Only this bit was revealed.

G/O Media may get a commission

Also Justin Simien is doing a Lando show and Leslye Headland’s show is called The Acolyte and takes place during the High Republic.

This story is developing…


For more, make sure you’re following us on our Instagram @io9dotcom.

geeky,Tech

via Gizmodo https://gizmodo.com

December 10, 2020 at 08:09PM

Loki’s First Trailer Brings the Asgardian Trickster Back Into the Fold

Loki’s First Trailer Brings the Asgardian Trickster Back Into the Fold

https://ift.tt/37QzTV7


Glorious indeed.
Screenshot: Marvel Studios

Trailer FrenzyA special place to find the newest trailers for movies and TV shows you’re craving.

The god of tricks is getting into the crime game, with a suitably wild trailer for his new series.

Starring Tom Hiddleston reprising his role as the Thor breakout, the series is set after Loki inadvertently gains access to the Tesseract, flinging him into the path of a mysterious investigative team known as the TVA.

Loki hits Disney+ in May 2021.


For more, make sure you’re following us on our Instagram @io9dotcom.

G/O Media may get a commission

geeky,Tech

via Gizmodo https://gizmodo.com

December 10, 2020 at 08:09PM

The Remington 870: A Timeless Pump-Action Shotgun

The Remington 870: A Timeless Pump-Action Shotgun

https://ift.tt/3gxMY9Q

One would have to argue long and hard to dispute that the classic Remington 870 pump-action shotgun is not, perhaps, the greatest slide-action smooth-bore shotgun of all time. Selling well into the millions, the Remington 870 has been delivered in a large variety of models from basic shotguns to magnums with numerous unique features that vary among them. The basic Remington 870 was first produced in 1950 as the Wingmaster model available in several gauges including 12, 16, or 20 gauge in barrel lengths of 26, 28, or 30 inches. These were 5 shotguns with various fixed-choke barrels including open bore, improved cylinder, modified, and full choke. Barrels were available in plain or vent-ribbed for an extra fee.

As mentioned, there have been so many models it is difficult to account for them all. These named pump-action shotguns included the Wingmaster, Express, Youth, Synthetic, Deer, Magnum, Express Magnum, Turkey, Express Combo, Laminate, Express Junior, Home Defense, Tactical, Express Super Magnum, Super Magnum Turkey, Super Slug, Special Purpose Marine Magnum, Sportsman, Small Gauge (28 and .410 gauge), Special Purpose, Magnum Duck, SPS-T Turkey, Special Purpose Deer, Lightweight, Special Field, Police, Blackhawk, Riot, Trap, and an unaccounted number of tribute and anniversary guns. See what I mean?

Remington 870 shotguns have seen action by law enforcement, military, and civilian use all these years. It is a sturdy design utilizing twin pump bars to insure smooth action for ejecting a spent shell and loading a fresh one. Shotshells are inserted under the receiver frame through a spring hinged loading gate into an under the barrel magazine hidden under the forearm stock. Plain sights are just a bead at the muzzle, though other models such as deer slug guns used other types of sights.

Wood furniture on the Remington 870s was everything from homely looking hardwood stocks to oiled walnut as well as highly lacquered walnut with pressed or cut checkering. Metal finishing was usually a nice polished bluing to a more utilitarian matte bead blasted dark blue or black finish depending on the model. Marine models were either parkerized or finished in a matte nickel type finish to resist salt rusting.

Barrels came in several lengths as mentioned – plain or with a raised sighting rib. Trap and skeet versions often had special raised ribs for sport shooting. Finishes were typically blued or matte. Remington much later in production introduced their unique RemChoke system which allowed the shooter to screw in various choke tubes from IC, Mod, Full, and a variety of specialty choke tubes such as Super Full or Turkey Full. This made the Remington 870 even more popular. The Remington 870 is a universal shotgun for all types of hunting from small game, upland birds, waterfowl, deer, and big game. It is a great home defense shotgun and truck gun. If you don’t have one, then it should certainly be on your buy list.

The post The Remington 870: A Timeless Pump-Action Shotgun appeared first on AllOutdoor.com.

guns

via All Outdoor https://ift.tt/2yaNKUu

December 10, 2020 at 01:19PM

Immediately After Moving To Texas, Elon Musk Announces Tesla AR-15

Immediately After Moving To Texas, Elon Musk Announces Tesla AR-15

https://ift.tt/36Zdndq


AUSTIN, TX—After years of fighting lame California politicians who want to lock everyone in their homes so they can’t go to space or build cool stuff, Tesla CEO Elon Musk announced he was moving to a land flowing with milk and honey called Texas. Almost immediately after the move, he announced a new product the whole world has been waiting for: the Tesla AR-15.

“Um… h-howdy, I think,” said Elon, expertly taking on the local dialect. “Y’all want a Tesla AR-15? You got it, partner!” 

The new firearm will look similar to a standard AR-15 but will in fact be a battery-powered railgun capable of firing 3 million rounds per minute. It will also feature a fingerprint sensor, Bluetooth capability, heat-seeking ammunition, and a chainsaw bayonet, to name a few.

“We really wanted to re-think self-defense,” said Musk. “This new firearm will be the go-to rifle for our SpaceX volunteers when they encounter hostile aliens. It’s also a celebration of the Second Amendment. If any federal authorities try to confiscate it, the rifle will automatically connect to the internet and file a lawsuit for you!”

The Federal Government has requested that Tesla at least remove the AI-powered “self-driving” feature on the firearm before selling it. 


fun

via The Babylon Bee https://babylonbee.com

December 9, 2020 at 02:03PM

Laravel Jetstream tutorial

Laravel Jetstream tutorial

https://ift.tt/33U4wrz


From laravel 8.0, Tylor Otwell introduced an official package for application scaffolding called Jetstream. It’s free and open-source. By this package, you can choose two stacks Laravel-Livewire or Laravel-Inertia. Jetstream views are designed with Tailwind CSS. Let’s see what are the features of Jetstream offer and how we can install and use it for our laravel application development.

Note If you are thinking, why Jetstream? there is already Laravel UI package for auth scaffolding. The answer is, still you can use Laravel UI package or an updated version Laravel Breeze for auth scaffolding but the Jetstream is another option with a lot of features included. Jetstream released with Laravel 8 and it’s not mandatory to use jetstream with Laravel 8. If you need the features described below then it’s highly recommended.

Laravel Jetstream features

  • Open-source, free and maintained by laravel team.
  • Designed with balde+tailwind CSS.
  • Available stacks (Livewire + Blade and Inertia + Vue)
  • Auth scaffolding
  • Profile management
  • Two-factor authentication
  • API token with Laravel Sanctum
  • Team management
  • Multi-session management
  • and more

 

Note If you are using older composer then update it first by composer self-update command.

Installation

After installing laravel 8 application, run the composer command given below for install the Laravel Jetstream package.

composer require laravel/jetstream

 

Choose your stack

Jetstream offers two stacks (Livewire + Blade and Inertia + Vue). You can choose a stack for your application scaffolding.

for Livewire run the command.

php artisan jetstream:install livewire
php artisan jetstream:install livewire --teams

for Inertia run the command.

php artisan jetstream:install inertia
php artisan jetstream:install inertia --teams

 

Now install the NPM dependencies and migration to finish the installation process for Jetstream.

npm install && npm run dev
php artisan migrate

 

Jetstream Visual

After successful installation of Jetstream, you will get the login, registration, profile management view looks like below which are designed with Tailwind CSS.

jetstream-registration.png

[Jetstream Registration View]

jetstream-login.png

[Jetstream Login View] 

jetstream-profile.png

[Jetstream Profile Management View]

 

Jetstream Features Config

To enable or disable a jetstream features is very easy. All the auth related features are listed in config/fortify.php config file.

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication(),
],

...

Jetstream features are listed in config/jetstream.php config file.

'features' => [
    Features::profilePhotos(),
    Features::api(),
    Features::teams(),
],
...

 

Jetstream package is really helpful to make the laravel application faster with popular stacks (Livewire and Inertia) in the Laravel community. Hope this post will help you to get an idea about what is Laravel Jetstream package is? is it important for you? and how you can install it in your laravel application. You can learn more about Laravel Jetstream by reading official Jetstream documentation. If you find this post helpful then please share with others.

programming

via Laravel News Links https://ift.tt/2dvygAJ

December 7, 2020 at 08:12PM

Splitting a large Laravel Livewire Component

Splitting a large Laravel Livewire Component

https://ift.tt/39smt4e


Published: Dec 1, 2020 by C.S. Rhymes

Sometimes, no matter what solution you use to build your system, there comes a point where everything tends to grow a bit big and edges towards being unmanageable. Luckily Livewire offers a solution to this problem.

What is Livewire?

Laravel Livewire offers a way to build dynamic interfaces, but instead of using a JavaScript library such as Vue or React, it allows developers to write their code in PHP components and Blade template files. It’s fantastic. If you haven’t used it before then I suggest you check it out.

What is the problem?

Lots of tutorials and examples tell you how to build something small, like a contact form or a todo list. This is absolutely fine as it allows the example to show the build from start to finish, but sometimes you get given a specification for a very large and complex system and are asked to build it.

Let’s use the example of a holiday car rental site. When you want to make your booking you need to store details of the customer, such as their name and address, the type of car you want to hire, as well as any extras such as additional insurance or even hotels for your stay.

One way of approaching this would be to create a single, large component with all the logic in and then a single view file that just keeps on getting longer and longer. It will probably work just fine, but there are some tools available that let you split this up into more manageable chunks.

Splitting the Component Class with Traits

Livewire v2 comes with a great feature of PHP called traits. Traits allow you to create a file that can be used within a class, giving the class the methods and properties of the trait, but allowing you to reuse the same trait from within multiple classes. This allows us to split the logic up between several smaller, more manageable files and ‘use’ them in the main component.

If we go back to our holiday car rental, we might need a trait that contains our methods for getting vehicle data, another for getting location information, such as addresses, or another for storing the customer’s details.

But Livewire traits take things even further too.

Rather than just allowing us to define our own methods we can make use of a naming convention to hook into the Livewire lifecycle hooks too.

We have said we will create a trait that is concentrated on vehicle information, but how do we make that data available to the rest of the component? We could call a method from the mount method of the main component class, but we could also do this in the trait by using the mount method of the trait.

If our trait was called VehicleInformation, then we can create a mountVehicleInformation method in our trait where we set the vehicle data to a public variable and it is then available to the main component.

trait VehicleInformation
{
    public $vehicles;

    public function mountVehicleInformation()
    {
        $this->vehicles = $this->getVehiclesData();
    }

    public function getVehiclesData()
    {
        // Get the vehicles data from somewhere
    }
}

From the example above, we can make use of $this->vehicles from with the main component class and $vehicles from within the blade view.

Splitting validation rules

Livewire gives us a way of creating rules as an array, which are validated when $this->validate(); is called.

class HolidayRental extends Component
{
    use VehicleInformation;

    public $vehicleType;

    protected $rules = [
        'vehicleType' => 'required',
        'startDate' => 'required|date',
    ];

    public function submit()
    {
        $this->validate();
    }
}

This works really nicely, but if we have a very large component, we could end up with may validation rules being defined in the main component class.

To help with the pattern we were using with traits, we could also extract the validation rules to the traits. There doesn’t seem to be anything built in to Livewire traits for this right now, but one method I have discovered is to define separate arrays in each trait and merge them in the constructor for the main component.

trait VehicleInformation
{
    public $vehicles;

    protected $vehicleInformationRules = [
        'vehicleType' => 'required',
    ];

    public function mountVehicleInformation()
    {
        $this->vehicles = $this->getVehiclesData();
    }

    public function getVehiclesData()
    {
        // Get the vehicles data from somewhere
    }
}
class HolidayRental extends Component
{
    use VehicleInformation;

    public $vehicleType;

    protected $rules = [
        'startDate' => 'required|date',
    ];

    public function __construct()
    {
        // Merge the component rules with rules from our trait
        $this->rules = array_merge($this->rules, $this->vehicleInformationRules);

        parent::__construct();
    }

    public function submit()
    {
        $this->validate();
    }
}

This also makes our validation rules more reusable across different components if needed.

Splitting the views

The view for the component is defined in the render method of the component. This is a single blade file.

class HolidayRental extends Component
{
    ...
    public function render()
    {
        return view('livewire.holiday-rental');
    }
}

For some reason it didn’t seem immediately obvious to me that you can use standard blade @include() from within the main livewire.holiday-rental blade view to include partials or sections of the form. I think this was due to my previous experience using Vue components where you have to play around passing state or syncing state between parent and child components. I was over thinking things. Blade files are views and the state is managed in the class so you can include as many subviews as you need and it will render them together.

Reusable sub components

One last thing to consider is how you can use the @include() tag to pass additional settings to a subview. In our example for holiday rentals we may need a search for hotels or car parks. We could build a single search results view that has a search box and displays an image, a title and a description for each result, but we could set what wire model the search box needs and which results to show by setting this in the @include() tag.

// livewire/holiday-rental.blade.php

<h2>Find a Hotel</h2>

@include('livewire.partials.search', ['searchModel' => 'hotelSearch', 'results' => $hotels])

<h2>Find a Car Park</h2>

@include('livewire.partials.search', ['searchModel' => 'carParkSearch', 'results' => $carParks])

// livewire/partials/search.blade.php

<input wire:model=">

@foreach($results as $result)
<div>
    <img src="" alt="" />
    <h3></h3>
    <p></p>
</div>
@endforeach

Planning it all out

Taking sometime to plan out and structure your project before you start diving into the code can bring benefits later on, reducing repetition and making your code more reusable and easier to maintain. I was lucky that I had some time available to spend a few days building a prototype to try out the above techniques before I started building my project for real. Hopefully it will pay off in the long run.

If there are any other techniques that you know of then please share them in the comments and hopefully you will enjoy working with Livewire as much as I do.

Photo by Sasha • Instagram.com/sanfrancisco from StockSnap

programming

via Laravel News Links https://ift.tt/2dvygAJ

December 7, 2020 at 08:12PM