Friday, 28 August 2020

How to Make Crud Application Laravel 7 using Livewire


In this post, we have describe a step by step guide for Creating CRUD (Create, Read, Update, Delete) Application in Laravel 7 framework by using Livewire package. We have already publish many tutorial on How to make crud application in Laravel framework but here we have come with brand new topic, this is because here we have use Livewire framework has been used with Laravel framework. In this post we will make Laravel Livewire Crud application from Scratch level. From this Laravel Livewire CRUD example, you can learn How to do CRUD operation in Laravel 7 framework by using Livewire package.

Now we have come on What is Livewire? So Livewire is a Laravel framework package and it is a full stack package for Laravel developer, and by using package Laravel programmer can perform both front-end side operation and back-end side operation in Laravel application. With the help of this Laravel Livewire package, we can run PHP script from front-end side without using Ajax or Javascript. Livewire completely send Ajax request for do all it's server side communication without write any line of Ajax script. By using this Laravel Livewire package, we will perform Insert Update Delete mysql database operation without refresh of web page without using single line of Ajax or jQuery or javascript code.

So now you have understand what is Laravel Livewire package and it is full stack framework in Laravel and by using this package we can make dynamic interfaces without loosing the comfort of Laravel framework. Now we have focused on Laravel Livewire CRUD application tutorial. From this tutorial you can learn how to use Livewire package in Laravel framework for perform Mysql insert update delete operation. For learn this things you have to follow following steps.





  1. Download Fresh Laravel 7 Framework
  2. Make Database Connection
  3. Create Mysql Table
  4. Create Model Class
  5. Install Livewire Package
  6. Create Livewire Component
  7. Run Laravel 7 Application




1. Download Fresh Laravel 7 Framework


In first step we have to download fresh copy of Laravel 7 framework. For download latest version of Laravel framework, we have to go to the command prompt and go to the directory in which you want to download Laravel 7 framework and write following command.


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


This command will make livewire directory and under that directory it will download Laravel 7 framework. So this way we can download latest version of Laravel framework.



2. Make Database Connection


In second step we have to make Mysql database connection in Laravel 7 framework. For this we have open .env and under this file we have to define following mysql database configuration.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


The above configuration will make database connection in Laravel 7 framework.

3. Create Mysql Table


After making Mysql database connection, now we want to create table in Mysql database from this Laravel 7 application. So, first want to create migration file. So for create migration file we have to go the command prompt and write following command.


php artisan make:migration sampledata


This command will create migration file under database/migrations directive. So we have to open that file and under that file we have to define table column details, which you can find below.

database/migrations/2020_08_28_060357_sampledata.php

<?php

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

class Sampledata extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sampledatas', function(Blueprint $table) {
            $table->id();
            $table->text('first_name');
            $table->text('last_name');
            $table->text('gender');
            $table->timestamps();
        });
    }

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



Now we want to migrate above table defination to mysql database. For this we have go to the command prompt and write following command.


php artisan migrate


Above command will migrate table defination to mysql database and create sampledatas table in define mysql database.

4. Create Model Class


In next step we have to create model class file for perform mysql database related operation. So for create model class file, we have to go to the command prompt and write following command.


php artisan make:model Sampledata


This command will create Sampledata.php model class file in app directory. In this file we have to define table column name which you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sampledata extends Model
{
    protected $fillable = ['first_name', 'last_name', 'gender'];
}

?>


5. Install Livewire Package


Now we have come on to the main part, how can we install Livewire package in Laravel 7 framework. So it is very easy, you have to just go to command prompt and write following command.


composer require livewire/livewire


This command will download Livewire package in Laravel 7 framework application and now we can use Livewire package in Laravel framework.

6. Create Livewire Component


For create livewire component in Laravel framework you should go to command prompt and run following command.


php artisan make:livewire posts


Above command will create two file in your project. One file at app/Http/Livewire/Posts.php and other file at resources/views/livewire/posts.blade.php. First file will use for back-end operation and second file will used for front-end operation for create CRUD application.

app/Http/Livewire/Posts.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;

use App\Sampledata;

class Posts extends Component
{
	public $sampledata, $first_name, $last_name, $gender, $data_id;

    public function render()
    {
    	$this->sampledata = Sampledata::all();
    	
        return view('livewire.posts');
    }

    public function resetInputFields()
    {
    	$this->first_name = '';
    	$this->last_name = '';
    	$this->gender = '';
    }

    public function store()
    {
    	$validation = $this->validate([
    		'first_name'		=>	'required',
    		'last_name'			=>	'required',
    		'gender'			=>	'required'
    	]);

    	Sampledata::create($validation);

    	session()->flash('message', 'Data Created Successfully.');

    	$this->resetInputFields();

    	$this->emit('userStore');
    }

    public function edit($id)
    {
        $data = Sampledata::findOrFail($id);
        $this->data_id = $id;
        $this->first_name = $data->first_name;
        $this->last_name = $data->last_name;
        $this->gender = $data->gender;
    }

    public function update()
    {
        $validate = $this->validate([
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'gender'        =>  'required'
        ]);

        $data = Sampledata::find($this->data_id);

        $data->update([
            'first_name'       =>   $this->first_name,
            'last_name'         =>  $this->last_name,
            'gender'            =>  $this->gender
        ]);

        session()->flash('message', 'Data Updated Successfully.');

        $this->resetInputFields();

        $this->emit('userStore');
    }

    public function delete($id)
    {
        Sampledata::find($id)->delete();
        session()->flash('message', 'Data Deleted Successfully.');
    }
}




resources/views/livewire/posts.blade.php

<div>
    @if(session()->has('message'))
        <div class="alert alert-success">{{ session('message') }}</div>
    @endif
    @include('livewire.create')

    @include('livewire.update')
    <br />
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Action</th>
            </tr>
        </thead>

        <tbody>
        	@foreach($sampledata as $data)
        	<tr>	
        		<td>{{ $data->first_name }}</td>
        		<td>{{ $data->last_name }}</td>
        		<td>{{ $data->gender }}</td>
        		<td>
                    <button data-toggle="modal" data-target="#updateModal" class="btn btn-primary btn-sm" wire:click="edit({{ $data->id }})">Edit</button>
                    <button wire:click="delete({{ $data->id }})" class="btn btn-danger btn-sm">Delete</button>
                </td>
        	</tr>
        	@endforeach
        </tbody>

    </table>
</div>




resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 7 CRUD App using Livewire</title>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

        @livewireStyles

    </head>
    <body>
        
        <br />
        <br />
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h2>Laravel 7 CRUD App using Livewire</h2>
                        </div>
                        <div class="card-body">
                            
                            @livewire('posts')
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        @livewireScripts

        <script type="text/javascript">

        window.livewire.on('userStore', () => {
            $('#createModal').modal('hide');
            $('#updateModal').modal('hide');
        });

        </script>
        
    </body>
</html>




resources/views/livewire/create.blade.php

<div align="right">
    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#createModal">Create</button>
</div>

<div wire:ignore.self id="createModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModalLabel">Add Data</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     <span aria-hidden="true close-btn">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="exampleFormControlInput1">First Name</label>
                        <input type="text" id="exampleFormControlInput1" class="form-control"  placeholder="Enter First Name" wire:model="first_name" />
                        @error('first_name')
                        <span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlInput2">Last Name</label>
                        <input type="text" id="exampleFormControlInput2" class="form-control" placeholder="Enter Last Name" wire:model="last_name" />
                        @error('last_name')<span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlInput3">Gender</label>
                        <select class="form-control" id="exampleFormControlInput3" wire:model="gender">
                            <option value="">Select</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                        @error('gender')<span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <button wire:click.prevent="store()" class="btn btn-success">Save</button>
                    <button type="button" class="btn btn-secondary close-btn" data-dismiss="modal">Close</button>
                </form>
            </div>
        </div>
    </div>
</div>


resources/views/livewire/update.blade.php

<div wire:ignore.self id="updateModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModalLabel">Edit Data</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     <span aria-hidden="true close-btn">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="exampleFormControlInput1">First Name</label>
                        <input type="text" id="exampleFormControlInput1" class="form-control"  placeholder="Enter First Name" wire:model="first_name" />
                        @error('first_name')
                        <span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlInput2">Last Name</label>
                        <input type="text" id="exampleFormControlInput2" class="form-control" placeholder="Enter Last Name" wire:model="last_name" />
                        @error('last_name')<span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlInput3">Gender</label>
                        <select class="form-control" id="exampleFormControlInput3" wire:model="gender">
                            <option value="">Select</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                        @error('gender')<span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <button wire:click.prevent="update()" class="btn btn-dark">Update</button>
                    <button type="button" class="btn btn-secondary close-btn" data-dismiss="modal">Close</button>
                </form>
            </div>
        </div>
    </div>
</div>


7. Run Laravel 7 Application


At the end of the steps, we have to run Laravep application. So for run Laravel application, first we should go to command prompt terminal and write following command.


php artisan serve


This command will start Laravel server and provide you a base url of your Laravel application, which you can find below.


http://127.0.0.1:8000/

So, you may go to browser and paste above base url and you can run above Laravel 7 Crud application which has been made by using Livewire package.


3 comments: