Laravel 8 Pluck Example Tutorial

Laravel 8 Pluck Example Tutorial

Hi Guys,

Today,i will learn how you can use pluck method in laravel 8. we are show simple example of pluck query builder example in laravel 8. you can table to get array in values using laravel pluck method.

It can get value column and key using pluck method.pluck method to returned collection single column or specify a custom key column following example.

Example: 1

Here example single column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $ids = \DB::table('posts')->pluck('id');

   dd($ids);
}
Output
array:[
    0 => 1
    1 => 2
    2 => 3
   ]
Example: 2

>Here example specify a custom key column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $users  = User::pluck('name','id');

   dd($users);
}
Output
array:4 [
    1 => "abc"
    2 => "xyz"
    3 => "mno"
  ]
It will help you...

JQuery Get and Set Image Src Tutorial

JQuery Get and Set Image Src Tutorial

Hi Guys,

Today, I will learn you how to get and set image src in jquery. We will show easy example of jquery get and set image src.The attr() method to get and change the image source in jQuery.

Get Image Src

In this example,I will Use the below script to get image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $imgsrc = $('img').attr('src');
    alert($imgsrc);
   });
});
Set the Image Src

In this example,I will Use the below script to set image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $("img").attr("src",'test.png');
  });
});
Full Example

Now,The following example will change the second image to the first image.

<html>
<head>
  <title> How to get and set image src attribute example</title>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
  <script>
    $(document).ready(function() {
      $('.btn').click(function(){
        $imgsrc = $('#first').attr('src');
        $("#second").attr("src",$imgsrc);
      });
    });
  </script>
  <style>
    .card{
      margin: 30px;
    }
  </style>
</head>
<body>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNSCowfKvdA_XwYJ4PViv9gQ-q50eeykM2E9FIdmSlIakgoW5QckWzOFc-WSBIZkBGkRXcefsoRVoPfP2UDM7qxUkoVc1IWSxhlZ0ZHx40BgJMO9eDkq1vQ18JWIhLW0C5W9owKiMdShmT/s0/Laravel+Custom+ENV+Variables+Tut.png" width="100" id="first" alt="Blog Image"">
  </div>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpipA6pqFifEWR4qswk86MZvHOBRC9JKkJhtSTDDoQYfe-mDETt1DGzsLy1X_i9bwNBdHnM812ftqImUIZqvjtBponL-G36pDZ4wVWzhjfKphtGgVf5NaL5J5q_2mEO9MX_2XpPe5nu04Q/s0/laravel-email-vali.png" width="100" id="second" alt="Blog Image">
  </div>
  <button type="type" class="btn">Get & Set image src</button>
</body>
</html>

It Will help you....

Laravel 8 Pagination Tutorial Example

Laravel 8 Pagination Tutorial Example

Hi Guys,

Today, I will learn you how to create pagination with laravel 8.If you want to full example of laravel 8 pagination example blade. if you have question about laravel 8 pagination with user table then i will give simple and easy example with solution for you. i explained simply step by step laravel 8 pagination tutorial. let’s talk about pagination in laravel 8.

We know pagination is a primary requisite of each and every project. so if you are a beginner with laravel than you must know how to utilize pagination in laravel 8 and what is other function that can utilize with laravel 8 pagination.

Now, In this example i will explain you from scratch how to working with laravel pagination. so let's follow bellow step by step tutorial for creating simple example of pagination with laravel 8.

Step 1: Add Route

First all of we put one route in one for list users with pagination. So simply add both routes in your route file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ProductController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('product', [ProductController::class, 'index']);
Step 2: Create Controller

Same things as above for route, here we will add one new method for route. index() will return users with pagination data, so let's add bellow:

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Product::paginate(5);
        return view('product.index',compact('data'));
    }
}
Step 3: Create Blade File

After create ProductController you need to create index blade file and put bellow code with links() so it will generate pagination automatically. So let's put it.

resources/views/index.blade.php
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <style type="text/css">
        .form-inline{
            display: inline;
        }
    </style>
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3>Laravel 8 Pagination Example Tutorial</h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th>#</th>
                                    <th>Product Name</th>
                                    <th>Product Price</th>
                                    <th>Product Details</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(!empty($products) && $products->count())
                                    @foreach($products as $key => $product)
                                        <tr>
                                            <td>{{ ++$key }}</td>
                                            <td>{{ $product->name }}</td>
                                            <td>{{ $product->price }}</td>
                                            <td>{{ $product->details }}</td>
                                            <td>
                                                  <button class="btn btn-danger btn-icon">
                                                    <i class="far fa-trash-alt text-white" data-feather="delete"></i>
                                                  </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                    @else
                                        <tr>
                                            <td colspan="10">There are no data.</td>
                                        </tr>
                                    @endif
                            </tbody>
                        </table>
                        {!! $products->links() !!}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Now you can run and check this example. it is a very simple and basic example.

If you are using bootstrap then you have to add useBootstrap() on service provider as like bellow:

app\Providers\AppServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
  
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

If you need advance used of pagination then you can see bellow how to use.

Pagination with appends parameter

{!! $data->appends(['sort' => 'votes'])->links() !!}

Pagination with appends request all parameters

{!! $data->appends(Request::all())->links() !!}

You can also see in advance details from here: Laravel 8 Pagination.

It will help you..

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Hii Dev,

In this blog, I will explain how can create dynamic multi level menu in laravel we will create example of multi level dynamic menu in laravel you can easy to make many level dynamic menu in laravel.

In this tutorial i simple create "menus" table and manage end level of parents and child menu with nested tree view structure in Laravel application. I use jquery for make tree view layout and child relationship with menu model for hierarchical data. I also add form for create new menu in tree view.I also create dynamic drop down menu using bootstrap nav.

If you are new in laravel then also you can do it simple and also simply customize it because this tutorial from scratch. You can simple following bellow step, you will multi level dynamic menu in your application as bellow preview and also you can check demo.

here following example step of multi level dynamic menu in laravel treeview

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create menus Table and Model

In this step we have to create migration and model for menus table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Menu -m
After this command you have to put bellow code in your migration file for create menus table. following path:/database/migrations/2020_01_10_102325_create_menus_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->integer('parent_id');
            $table->timestamps();
        });
    }

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Menu table.

following path:/app/Models/Menu.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    protected $fillable = ['title','parent_id'];

    public function childs() {
        return $this->hasMany('App\Menu','parent_id','id') ;
    }
}
Step 3: Create Route

In this is step we need to create route for tree menu show layout file , create menu for post method route and show dynamic menus.

following path:/routes/web.php
<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\MenuController;
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
    Route::get('menus',[MenuController::class,'index']);
    Route::get('menus-show',[MenuController::class,'show']);
    Route::post('menus',[MenuController::class,'store'])->name('menus.store');
Step 4: Create Controller

Here this step now we should create new controller as MenuController,So run bellow command for generate new controller

php artisan make:controller MenuController

now this step, this controller will manage menu layout and create menu with validation with post request,bellow content in controller file. i added three method in this controller as listed bellow:

1)index() 2)store() 3)show() following path:/app/Http/Controllers/MenuController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Menu;

class MenuController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(){
   
       $menus = Menu::where('parent_id', '=', 0)->get();
       $allMenus = Menu::pluck('title','id')->all();
       return view('menu.menuTreeview',compact('menus','allMenus'));
   
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
       $request->validate([
           'title' => 'required',
        ]);

       $input = $request->all();
        $input['parent_id'] = empty($input['parent_id']) ? 0 : $input['parent_id'];
        Menu::create($input);
         return back()->with('success', 'Menu added successfully.');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show()
    {
        $menus = Menu::where('parent_id', '=', 0)->get();
        return view('menu.dynamicMenu',compact('menus'));
    }
}
Step 5: Create View

In this step, we have to create menu folder in total four blade file as listed bellow:

1)menuTreeview.blade.php

2)manageChild.blade.php

3)dynamicMenu.blade.php

4)menusub.blade.php

This both blade file will help to render menu tree structure, so let's create both file view file and put bellow code.

following path:/resources/views/menu/menuTreeview.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Multi Level Dynamic Menu In Laravel Treeview</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   <link href="/css/treeview.css" rel="stylesheet">
</head>
<body class="bg-dark">
<div class="container">
   <div class="row">
      <div class="col-md-10 offset-md-1 mt-4">
         <div class="card">
            <div class="card-header">
               <h5>Multi Level Dynamic Menu In Laravel Treeview</h5>
            </div>
            <div class="card-body">
               <div class="row">
                  <div class="col-md-6">
                     <h5 class="mb-4 text-center bg-success text-white ">Add New Menu</h5>
                     <form accept="{{ route('menus.store')}}" method="post">
                        @csrf
                         @if(count($errors) > 0)
                                  <div class="alert alert-danger  alert-dismissible">
                                      <button type="button" class="close" data-dismiss="alert">×</button>
                                      @foreach($errors->all() as $error)
                                              {{ $error }}<br>
                                      @endforeach
                                  </div>
                              @endif
                          @if ($message = Session::get('success'))
                           <div class="alert alert-success  alert-dismissible">
                               <button type="button" class="close" data-dismiss="alert">×</button>   
                                   <strong>{{ $message }}</strong>
                           </div>
                        @endif
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Title</label>
                                 <input type="text" name="title" class="form-control">   
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Parent</label>
                                 <select class="form-control" name="parent_id">
                                    <option selected disabled>Select Parent Menu</option>
                                    @foreach($allMenus as $key => $value)
                                       <option value="{{ $key }}">{{ $value}}</option>
                                    @endforeach
                                 </select>
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <button class="btn btn-success">Save</button>
                           </div>
                        </div>
                     </form>
                  </div>
                  <div class="col-md-6">
                     <h5 class="text-center mb-4 bg-info text-white">Menu List</h5>
                      <ul id="tree1">
                         @foreach($menus as $menu)
                            <li>
                                {{ $menu->title }}
                                @if(count($menu->childs))
                                    @include('menu.manageChild',['childs' => $menu->childs])
                                @endif
                            </li>
                         @endforeach
                        </ul>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<script src="/js/treeview.js"></script>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/manageChild.blade.php
  <ul>
  @foreach($childs as $child)
     <li>
         {{ $child->title }}
     @if(count($child->childs))
              @include('manageChild',['childs' => $child->childs])
          @endif
     </li>
  @endforeach
  </ul>

After This both blade file will help to render dynamic drop down menu view file, so let's create both file view file and put bellow code.

following path:/resources/views/menu/dynamicMenu.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://bootstrapthemes.co/demo/resource/bootstrap-4-multi-dropdown-hover-navbar/css/bootstrap-4-hover-navbar.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
<nav class="navbar navbar-expand-md navbar-light bg-light btco-hover-menu">
    <a class="navbar-brand" href="#">Nicesnippets.com</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav">
            @foreach($menus as $menu)
            <li class="nav-item dropdown">
                <a class="nav-link {{ count($menu->childs) ? 'dropdown-toggle' :'' }}" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                   {{ $menu->title }}
                </a>
                <ul class="dropdown-menu " aria-labelledby="navbarDropdownMenuLink">
                  @if(count($menu->childs))
                    @include('menu.menusub',['childs' => $menu->childs])
                  @endif
                </ul>
            </li>
            @endforeach
        </ul>
    </div>
</nav>
<div style="position: absolute; left:2%; top:55%;">
  <h2 class="bg-white p-2 shadow-lg rounded">Multi Level Dynamic Menu In Laravel Treeview</h2>
</div>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/menusub.blade.php
 @foreach($childs as $child)
 <li>
      <a class="dropdown-item {{ count($child->childs) ? 'dropdown-toggle' :'' }}" href="#" style="border:1px solid #ccc;">{{ $child->title }}</a>
       @if(count($child->childs))
          <ul class="dropdown-menu">
              <li>
                 <a class="dropdown-item" href="#" style="position: absolute;">
                       @include('menu.menusub',['childs' => $child->childs])
                    </a>
                </li>
            </ul>
        @endif
   </li>
 @endforeach
Preview:Menu treeview hierarchical structure Step 6: Add CSS and JS File

In last step, we have to add one css file and one js file for treeview design. I simply use bootsnipp css and js code, so let's create css and js file as following path:

following path:public/css/treeview.css
.tree, .tree ul {
    margin:0;
    padding:0;
    list-style:none
}
.tree ul {
    margin-left:1em;
    position:relative
}
.tree ul ul {
    margin-left:.5em
}
.tree ul:before {
    content:"";
    display:block;
    width:0;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    border-left:1px solid
}
.tree li {
    margin:0;
    padding:0 1em;
    line-height:2em;
    color:#369;
    font-weight:700;
    position:relative
}
.tree ul li:before {
    content:"";
    display:block;
    width:10px;
    height:0;
    border-top:1px solid;
    margin-top:-1px;
    position:absolute;
    top:1em;
    left:0
}
.tree ul li:last-child:before {
    background:#fff;
    height:auto;
    top:1em;
    bottom:0
}
.indicator {
    margin-right:5px;
}
.tree li a {
    text-decoration: none;
    color:#369;
}
.tree li button, .tree li button:active, .tree li button:focus {
    text-decoration: none;
    color:#369;
    border:none;
    background:transparent;
    margin:0px 0px 0px 0px;
    padding:0px 0px 0px 0px;
    outline: 0;
}

This is require js file

following path:public/js/treeview.js
$.fn.extend({
    treed: function (o) {
      
        var openedClass = 'glyphicon-minus-sign';
        var closedClass = 'glyphicon-plus-sign';
      
        if (typeof o != 'undefined'){
          if (typeof o.openedClass != 'undefined'){
            openedClass = o.openedClass;
          }
          if (typeof o.closedClass != 'undefined'){
            closedClass = o.closedClass;
          }
        }
      
        /* initialize each of the top levels */
        var tree = $(this);
        tree.addClass("tree");
        tree.find('li').has("ul").each(function () {
            var branch = $(this);
            branch.prepend("");
            branch.addClass('branch');
            branch.on('click', function (e) {
                if (this == e.target) {
                    var icon = $(this).children('i:first');
                    icon.toggleClass(openedClass + " " + closedClass);
                    $(this).children().children().toggle();
                }
            })
            branch.children().children().toggle();
        });
        /* fire event from the dynamically added icon */
        tree.find('.branch .indicator').each(function(){
            $(this).on('click', function () {
                $(this).closest('li').click();
            });
        });
        /* fire event to open branch if the li contains an anchor instead of text */
        tree.find('.branch>a').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
        /* fire event to open branch if the li contains a button instead of text */
        tree.find('.branch>button').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
    }
});
/* Initialization of treeviews */
$('#tree1').treed();

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

open bellow URL to create menu on your browser:

http://localhost:8000/menus

Now you can open bellow URL to dropdown nav menu on your browser:

http://localhost:8000/menus-show

It will help you...

Laravel Arr where() function Example

Laravel Arr where() function Example

Hi Dev,

Today,I will learn you how to use laravel array where() function example. We will show example of array where function in laravel.The Arr::where method filters an array using the given Closure:

Here, I will give you full example for simply Arr where() method in laravel as bellow.

Example
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\FileController;
use Illuminate\Support\Arr;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $array = [100, 'Laravel', 300, 'Php', 500];
        $filtered = Arr::where($array, function ($value, $key) {
                return is_string($value);
        });

        print_r($filtered);
        //[1 => 'Laravel', 3 => 'Php']

        $array2 = [100, '200', 300, '400', 500];

        $filtered2 = Arr::where($array2, function ($value, $key) {
            return is_string($value);
        });

        print_r($filtered2);
        // [1 => '200', 3 => '400']
    }
}
Output
"[1 => '200', 3 => '400']"
" [1 => 'Laravel', 3 => 'Php']"

It Will help you...

Laravel 8 Model Observers Example Tutorial

Laravel 8 Model Observers Example Tutorial

Hi Dev,

Nowdays,i will analyze you a way to use laravel 8 observers. this example will help you a way to use laravel 8 model observers. i would love to expose you what is observers in laravel 8. This tutorial will come up with simple instance of laravel eight model observers.

We can come up with very simple definition and use of laravel observers is, when you want to generate slug or auto generate precise identification or something like common sense add earlier than or after create document then observers will help you. i can come up with bellow events that provide via observers and easy instance bellow.

Here, i will give you complete instance for in reality model Observers the usage of Laravel eight as bellow.

Eloquent Hook

->Retrieved: after a record has been retrieved.

->Creating: before a record has been created.

->Created: after a record has been created.

->Updating: before a record is updated.

->Updated: after a record has been updated.

->Saving: before a record is saved (either created or updated).

->Saved: after a record has been saved (either created or updated).

->Deleting: before a record is deleted or soft-deleted.

->Deleted: after a record has been deleted or soft-deleted.

->Restoring: before a soft-deleted record is going to be restored.

->Restored: after a soft-deleted record has been restored.

Example:

Now In this blog,we will see simple example, i have one Food model and it has name, slug, price and unique_id column. so i need to create one record with name an price only. but when it's create i need to generate slug from name and auto generate unique_id.

app/Models/Food.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Food extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'price', 'slug', 'unique_id'
    ];
}

Create observers class for Food. So, create bellow command:

php artisan make:observer FoodObserver --model=Food
app/Observers/FoodObserver.php
<?php
  
namespace App\Observers;
  
use App\Models\Food;
  
class FoodObserver
{
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function creating(Food $food)
    {
        $food->slug = \Str::slug($food->name);
    }
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function created(Food $food)
    {
        $food->unique_id = 'PR-'.$food->id;
        $food->save();
    }
  
    /**
     * Handle the Food "updated" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function updated(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function deleted(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "restored" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function restored(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "force deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function forceDeleted(Food $food)
    {
          
    }
}

Register Observers class on provider.

app/Providers/EventServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Observers\FoodObserver;
use App\Models\Food;
  
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
  
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        Food::observe(FoodObserver::class);
    }
}

Create Demo Route:

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FoodController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('food', [FoodController::class, 'index']);

Create Controller Route:

app/Http/Controllers/FoodController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Food;
use Illuminate\Http\Request;
  
class FoodController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
  
        $food = Food::create([
            'name' => 'Milk',
            'price' => 30
        ]);
  
        dd($food);
    }
}

Now you can run project.

It will help you...

Laravel WhereHas Eloquent Example

Laravel WhereHas Eloquent Example

Hi Guys,

Today,I will learn you how to laravel wherehas eloquent. you will learn about laravel eloquent whereHas() with example. we show example of wherehas eloquent in laravel.you can easily use laravel wherehas eloquent.

Here I will give you example of laravel wherehas eloquent.

Example WhereHas Eloquent

Now this example, If you need even more power, you may use the whereHas methods to put "where" conditions on your has queries.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Country;

class BlogController extends Controller
{  

  /**
   * Write code on Method
   *
   * @return response()
   */
   public function index()
   {
       $country = Country::whereHas('blogs', function($q){
                      $q->where('name', '=', 'Good Info');
                   })->get();  
       dd($country->toArray());
   }
}
Output
array:1 [
  0 => array:5 [
    "id" => 1
    "name" => "test"
    "blogs_id" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

It will help you..

Laravel 8 Download File Example

Laravel 8 Download File Example

Hi Dev,

In this blog,I'm able to examine you how to download report in laravel 8. we are able to display instance of reaction download with document in laravel 8.We now and again require to go back reaction with download document from controller technique like generate invoice and deliver to download or and so on.Laravel eight provide us response() with down load approach that way we are able to do it.

Here, First argument of down load() I ought to give route of down load document. we will rename of download record through passing second argument of download(). We can also set headers of file with the aid of passing third argument.

So, first i am going to create new route for our instance as like bellow:

routes/web.php
<?php
use App\Http\Controllers\DownloadFileController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|

Route::get('/file-download', [DownloadFileController::class, 'index'])->name('file.download.index');

Now,I have to add one method "downloadFile()" in my DownloadFileController. If you don't have DownloadFileController then you can use your own controller as like bellow:

App\Http\Controllers\DownloadFileController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DownloadFileController extends Controller
{
    public function index()
    {
    	$filePath = public_path("dummy.pdf");
    	$headers = ['Content-Type: application/pdf'];
    	$fileName = time().'.pdf';

    	return response()->download($filePath, $fileName, $headers);
    }
}

It will help you...

Laravel Validation timezone Example

Laravel Validation timezone Example

Hi Guys,

Today, I will learn you to create validation timezone in laravel.we will show example of laravel validation timezone.The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

Here, I will give you full example for simply timezone validation in laravel bellow.

solution
$request->validate([
  'time_zone' => 'timezone',
]);
Route : routes/web.php
Route::get('form/create','FormController@index');
Route::post('form/store','FormController@store')->name('form.store');
Controller : app/Http/Controllers/FormController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FormController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'time_zone' => 'timezone'
        ]);
      dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scrtimezonet src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scrtimezonet>
  <scrtimezonet src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scrtimezonet>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation timezone Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Your Timezone:</label>
                      <input name="time_zone" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Laravel Custom Middleware Tutorial Example

Laravel Custom Middleware Tutorial Example

Hi guys,

In this blog,I can create custom middleware in laravel, we are able to discover ways to create custom middleware in laravel utility and the way to use middleware in laravel based mission. truely create one custom middleware and take a look at language in query string.

clearly laravel middleware filter out all of the http request in laravel based totally tasks. as an instance when user is do any request that point middleware take a look at person is loggedin or now not and redirect therefore. Any person is not loggedin but he need to get entry to to dashboard or different things in projects that point middleware filter request redirect to consumer.

on this laravel middleware educational, we can supply a example of active or inactive users. Now we can name middleware in routes to restriction logged person to get right of entry to that routes, if he/she is blocked by way of admin.

In this laravel middleware tutorial, we will give a example of active or inactive users. Now we will call middleware in routes to restrict logged user to access that routes, if he/she is blocked by admin.

Step:1 Create Middleware

In this step, We have to create custom middleware in laravel based project. So let’s open your command prompt and run below command :

php artisan make:middleware CheckStatus
Step:2 Register Middleware

After successfully create middleware, go to app/http/kernel.php and register your custom middleware here :

app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    ....
 
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'checkStatus' => \App\Http\Middleware\CheckStatus::class,
    ];
}
?>
Step:3 Implement logic In Middleware

After successfully register your middleware in laravel project, go to app/http/middleware and implement your logic here :

app/Http/Middleware/CheckStatus.php
<?php
namespace App\Http\Middleware;
use Closure;

class CheckStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->user()->status == 'active') {
            return $next($request);
        }
            return response()->json('Your account is inactive');
 
    }
}
?>
Step:4 Create Route

In this step, simply we will create a route and use custom middleware here. Filter http every request and protect routes :

<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\HomeController;

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
 
    Route::middleware(['checkStatus'])->group(function(){
    Route::get('home', 'HomeController@home');
});
Step:5 Add Method in Controller

Now we will create one method name language and let’s check :

app/Http/Controllers/HomeController.php
<?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 
 class HomeController extends Controller
 {
     public function home()
     {
         dd('You are active');
     }
 }
?>

We have successfully create custom middleware in laravel based project with simple example. run the example.

It Will help you....

Laravel Custom Forgot Password Email Function Example

Laravel Custom Forgot Password Email Function Example

Hi Guys,

Today, I will learn you how to custom forgot & reset password in laravel. we will show example of laravel custom forgot & reset password. you can easliy create custom forgot & reset password in laravel. This post will give you simple example of how to create custom forgot password in laravel. step by step explain laravel custom reset password email.

I will help to creating custom reset password function in php laravel. so basically, you can also create custom forget password with different models too.

Here, I will give you full example for simply laravel custom forgot & reset password as bellow.

Step 1: Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel Laravel8TypeheadTutorial
Step 2: Database Configuration

In this step, configure database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3: Create "password_resets" table

basically, it will already created "password_resets" table migration but if it's not created then you can create new migration as like bellow code:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('password_resets');
    }
}
Step 4: Create Route

In this is step we need to create custom route for forget and reset link. so open your routes/web.php file and add following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\Auth\ForgotPasswordController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('forget-password', [ForgotPasswordController::class, 'showForgetPasswordForm'])->name('forget.password.get');
Route::post('forget-password', [ForgotPasswordController::class, 'submitForgetPasswordForm'])->name('forget.password.post'); 
Route::get('reset-password/{token}', [ForgotPasswordController::class, 'showResetPasswordForm'])->name('reset.password.get');
Route::post('reset-password', [ForgotPasswordController::class, 'submitResetPasswordForm'])->name('reset.password.post');
Step 5: Create Controller

Now step, we need to create ForgotPasswordController and add following code on that file:

app/Http/Controllers/Auth/ForgotPasswordController.php
<?php 
  
namespace App\Http\Controllers\Auth; 
  
use App\Http\Controllers\Controller;
use Illuminate\Http\Request; 
use DB; 
use Carbon\Carbon; 
use App\Models\User; 
use Mail; 
use Hash;
use Illuminate\Support\Str;
  
class ForgotPasswordController extends Controller
{
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function showForgetPasswordForm()
      {
         return view('auth.forgetPassword');
      }
  
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function submitForgetPasswordForm(Request $request)
      {
          $request->validate([
              'email' => 'required|email|exists:users',
          ]);
  
          $token = Str::random(64);
  
          DB::table('password_resets')->insert([
              'email' => $request->email, 
              'token' => $token, 
              'created_at' => Carbon::now()
            ]);
  
          Mail::send('email.forgetPassword', ['token' => $token], function($message) use($request){
              $message->to($request->email);
              $message->subject('Reset Password');
          });
  
          return back()->with('message', 'We have e-mailed your password reset link!');
      }
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function showResetPasswordForm($token) { 
         return view('auth.forgetPasswordLink', ['token' => $token]);
      }
  
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function submitResetPasswordForm(Request $request)
      {
          $request->validate([
              'email' => 'required|email|exists:users',
              'password' => 'required|string|min:6|confirmed',
              'password_confirmation' => 'required'
          ]);
  
          $updatePassword = DB::table('password_resets')
                              ->where([
                                'email' => $request->email, 
                                'token' => $request->token
                              ])
                              ->first();
  
          if(!$updatePassword){
              return back()->withInput()->with('error', 'Invalid token!');
          }
  
          $user = User::where('email', $request->email)
                      ->update(['password' => Hash::make($request->password)]);
 
          DB::table('password_resets')->where(['email'=> $request->email])->delete();
  
          return redirect('/login')->with('message', 'Your password has been changed!');
      }
}
Step 6: Email Configuration

In this step,we will add email configuration on env file, because we will send email to reset password link from controller.

.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
MAIL_USERNAME=example@hotmail.com
MAIL_PASSWORD=123456789
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=example@hotmail.com
Step 7: Create Blade Files

Now in this step,we need to create blade files for layout, login, register and home page. so let's create one by one files.


<html>
<head>
    <title>Laravel</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <style type="text/css">
        @import url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);
  
        body{
            margin: 0;
            font-size: .9rem;
            font-weight: 400;
            line-height: 1.6;
            color: #212529;
            text-align: left;
            background-color: #f5f8fa;
        }
        .navbar-laravel
        {
            box-shadow: 0 2px 4px rgba(0,0,0,.04);
        }
        .navbar-brand , .nav-link, .my-form, .login-form
        {
            font-family: Raleway, sans-serif;
        }
        .my-form
        {
            padding-top: 1.5rem;
            padding-bottom: 1.5rem;
        }
        .my-form .row
        {
            margin-left: 0;
            margin-right: 0;
        }
        .login-form
        {
            padding-top: 1.5rem;
            padding-bottom: 1.5rem;
        }
        .login-form .row
        {
            margin-left: 0;
            margin-right: 0;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar-laravel">
    <div class="container">
        <a class="navbar-brand" href="#">Laravel</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
   
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav ml-auto">
                @guest
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('register') }}">Register</a>
                    </li>
                @else
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('logout') }}">Logout</a>
                    </li>
                @endguest
            </ul>
        </div>
    </div>
</nav>
@yield('content')
</body>
</html>
resources/views/auth/forgetPassword.blade.php
@extends('layout')
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Reset Password</div>
                  <div class="card-body">
  
                    @if (Session::has('message'))
                         <div class="alert alert-success" role="alert">
                            {{ Session::get('message') }}
                        </div>
                    @endif
  
                      <form action="{{ route('forget.password.post') }}" method="POST">
                          @csrf
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Send Password Reset Link
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection
resources/views/auth/forgetPasswordLink.blade.php
@extends('layout')
  
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Reset Password</div>
                  <div class="card-body">
  
                      <form action="{{ route('reset.password.post') }}" method="POST">
                          @csrf
                          <input type="hidden" name="token" value="{{ $token }}">
  
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password" class="form-control" name="password" required autofocus>
                                  @if ($errors->has('password'))
                                      <span class="text-danger">{{ $errors->first('password') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password-confirm" class="form-control" name="password_confirmation" required autofocus>
                                  @if ($errors->has('password_confirmation'))
                                      <span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Reset Password
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection
resources/views/email/forgetPassword.blade.php
<h1>Forget Password Email</h1>
   
<p>You can reset password from bellow link:</p>
<a href="{{ route('reset.password.get', $token) }}">Reset Password</a>
resources/views/auth/login.blade.php
@extends('layout')
  
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Login</div>
                  <div class="card-body">
  
                      <form action="{{ route('login.post') }}" method="POST">
                          @csrf
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password" class="form-control" name="password" required>
                                  @if ($errors->has('password'))
                                      <span class="text-danger">{{ $errors->first('password') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <div class="col-md-6 offset-md-4">
                                  <div class="checkbox">
                                      <label>
                                          <input type="checkbox" name="remember"> Remember Me
                                      </label>
                                  </div>
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <div class="col-md-6 offset-md-4">
                                  <div class="checkbox">
                                      <label>
                                          <a href="{{ route('forget.password.get') }}">Reset Password</a>
                                      </label>
                                  </div>
                              </div>
                          </div>
    
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Login
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/
It will help you...

Laravel Calculate Time Difference Between Two Dates In Hours And Minutes

Laravel Calculate Time Difference Between Two Dates In Hours And Minutes

Hello Dev,

In this blog, i'm able to explain the way to calculate time difference among two dates in hours and mins in laravel,we will show calculate time distinction among dates in hours and mins.we can carbon the use of time difference between dates in hours and minutes.

I'm able to show difference among dates in hours and minutes the use of diffForHumans and diff techniques in laravel we will diffForHumans technique to reveal distinction between two dates in hours and mins.

Here following instance of calculate time distinction between two dates in hours and minutes in laravel

Example: 1

Now the example of diffForHumans method using time difference between two dates in hours and minutes in laravel.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{

    $startTime = Carbon::parse('2020-02-11 04:04:26');
    $endTime = Carbon::parse('2020-02-11 04:36:56');

    $totalDuration = $endTime->diffForHumans($startTime);
    dd($totalDuration);
}
Output
"32 minutes after"
Example: 2

Now the example of diff method using time difference between two dates in hours and minutes in laravel.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{

    $startTime = Carbon::parse('2020-02-11 04:04:26');
    $endTime = Carbon::parse('2020-02-11 04:36:56');

    $totalDuration =  $startTime->diff($endTime)->format('%H:%I:%S')." Minutes";
    dd($totalDuration);
}
Output
"00:32:30 Minutes"

It will help you...

Laravel Please Provide A Valid Cache Path Error

Hello guys,

In this blog , i'm able to display you the way to solution Please provide a valid Cache pathblunders in laravel.a few errors happens on deploying laravel initiatives on webservers. So don’t worry about that this mistake “please provide a legitimate cache route laravel“.

The cause for occurring this mistake “please offer a legitimate cache direction laravel” error occurs. because internal your laravel mission, does not have some directories/folders. The directories and folders are the subsequent:

->YourProjectFolder/storage/framework/

->sessions

->views

->cache

This blog will provide you 3 solutions to fix this “please provide a valid cache path laravel” on your server or virtual host.

Solution: 1

In the first solution, you can create a framework folder inside your laravel-project-name/storage/ directory by using the following command:

cd storage/
mkdir -p framework/{sessions,views,cache}

Then set permissions to the directory. To allow Laravel to write data in the above-created directory. So run the following command on your command prompt:

cd storage/
chmod -R 775 framework
chown -R www-data:www-data framework
Solution No: 2

In the solution number 2, You can create mutually directories inside your laravel project folder.

So, Navigate to your project root directory and open Storage folder.

Then, Create framework directory/folder inside the storage folder.

After that, create the following directories inside the framework folder.

->sessions

->views

->cache

cache/data:- Inside cache folder, create a new directory/folder named data.

Finally, open your terminal and run the following command to clear all the cache:

php artisan cache:clear
Solution No: 3

In this solution number 3, open your terminal and run the following

commands:
sudo mkdir storage/framework
sudo mkdir storage/framework/sessions
sudo mkdir storage/framework/views
sudo mkdir storage/framework/cache
sudo mkdir storage/framework/cache/data

sudo chmod -R 777 storage 

It will help you..

Laravel Ajax Form Submit With Validation Example

Laravel Ajax Form Submit With Validation Example

Hi Dev,

In this blog,i will indicates how you can submit the form the usage of ajax with jquery validation(patron facet) in laravel. we can ajax post form after validation in laravel. you could clean laravel ajax shape publish. you could submit the shape the usage of jquery and with out the complete page refresh. whilst we publish an ajax form in laravel, we will upload csrf token in ajax request.

here following example to laravel ajax shape submit with validation.

Step 1: Create Model and Migration

here this step, we will create one model and migration name Post. Use the below following command and create it

php artisan make:model Post -m

Next,Open post migration file and put the below code. here following path of migration file

Path: /database/migrations/2020_01_02_095534_create_posts_table.php
<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Next, go to app/Post.php and open post model file and put the below code. here following path of model fille Path:/app/Post.php
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title','body'];
}
Step 2: Create Route

Create two routes one for show form and the second route send data to the server:

here following path of route fille

Path:/routes/web.php
Route::get('ajax-form-submit', 'PostController@index');
Route::post('save-form', 'PostController@store');
Step 3:Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller PostController 
Step 4:Controller Code

here this step,we will create two methods inside the controller first index method is used to display contact form and second store method is used to store data in the mysql database

here following path of Controller fille

Path:/app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
   
  public function index()
  {
  	return view('ajaxPostForm');
  }

  public function store(Request $request)
  {
     $input = $request->all();
     $request->validate([
       'title' => 'required',
       'body' => 'required'
     ]);
     $check = Post::create($input);
     $arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' =>false);
     if($check){ 
        $arr = array('msg' => 'Successfully Form Submit', 'status' => true);
     }
    return response()->json($arr);
  }
}
Step 5:Create a blade view

In this step, we will create one blade file name ajaxPostForm.blade.php.

In this ajax form, we will implement a jquery submit handler. first, we will validate form using jquery validation and second is to submit an ajax form using submit handler.

here following path of blade fille

Path:/resources/views/ajaxPostForm.blade.php
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Post Form </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
  <style>
   .error{ color:red; } 
  </style>
</head>
<body>
   <div class="container">
      <div class="row">
         <div class="col-md-6 mt-3 offset-md-3">
            <div class="card">
               <div class="card-header bg-dark text-white">
                  <h6>laravel Ajax Form Submission Example </h6>
               </div>
               <div class="card-body">
                  <form id="post-form" method="post" action="javascript:void(0)">
                     @csrf
                     <div class="row">
                        <div class="col-md-12">
                           <div class="alert alert-success d-none" id="msg_div">
                                   <span id="res_message"></span>
                              </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Title<span class="text-danger">*</span></label>
                              <input type="text" name="title" placeholder="Enter Title" class="form-control">
                              <span class="text-danger p-1">{{ $errors->first('title') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Body<span class="text-danger">*</span></label>
                              <textarea class="form-control" rows="3" name="body" placeholder="Enter Body Text"></textarea>
                              <span class="text-danger">{{ $errors->first('body') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <button type="submit" id="send_form" class="btn btn-block btn-success">Submit</button>
                        </div>   
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </div>
</body>
<script>
   if ($("#post-form").length > 0) {
    $("#post-form").validate({
      
    rules: {
      title: {
        required: true,
        maxlength: 50
      },
      body: {
        required: true,
        maxlength: 250
      }
    },
    messages: {
      title: {
        required: "Please Enter Name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },
      body: {
        required: "Please Enter Body",
        maxlength: "Your last body maxlength should be 250 characters long."
      },
    },
    submitHandler: function(form) {
     $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $('#send_form').html('Sending..');
      $.ajax({
        url: '/save-form' ,
        type: "POST",
        data: $('#post-form').serialize(),
        success: function( response ) {
            $('#send_form').html('Submit');
            $('#res_message').show();
            $('#res_message').html(response.msg);
            $('#msg_div').removeClass('d-none');
 
            document.getElementById("post-form").reset(); 
            setTimeout(function(){
            $('#res_message').hide();
            $('#msg_div').hide();
            },10000);
        }
      });
    }
  })
}
</script>
</html>

We will validate form data before submit, check validation like mobile number contains only digits not accept the character. The name filed contains 50 characters only. we will use post method in laravel ajax with csrf token

Step 6:Start Server

In this step, we will use the php artisan serve command.

php artisan serve

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/ajax-form-submit

It will help you...

How To Set Bcc And CC Mail Address In Laravel ?

How To Set Bcc And CC Mail Address In Laravel ?

Hi Guys,

Today,I will learn you how to set bcc And cc Mail Address In Laravel Mail. I can show you set bcc (blind carbon copy) and cc (carbon copy) mail address in laravel mail.You can easy get laravel mail in cc and bcc here the example

Laravel Send Mail using Mailable Class Example

You can tell Set Bcc And Cc Mail Address In Laravel Mail before learn how to send Mail here this link

Link:https://itwebtuts.blogspot.com/2021/04/laravel-8-send-email-example-tutorial.html You are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients all within a single, chained method call: Solution Here, this cc() and bcc() method to you can set bcc and cc mail address in laravel mail.
 /**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function itTestMail()
{
    $myUsers = 'xzy@gmail.com';
    $myMoreUsers ='abc@gmail.com';
    $evenMyMoreUsers = 'pqr@gmail.com';
    
    Mail::to($myUsers)
        ->cc($moreMyUsers)
        ->bcc($evenMyMoreUsers)
        ->send(new MyTestMail());
    
    dd("Mail Send Successfully");
}
It will help you...

Laravel Ajax CRUD Tutorial Using Datatable Example

Laravel Ajax CRUD Tutorial Using Datatable Example

Hello Dev,

Here, i'm able to manual you step by step ajax crud operations in laravel eight with modal & pagination. we are able to create jquery ajax crud with modals using datatables js in laravel eight. we can definitely write jquery ajax request for crud with yajra datatable laravel 8.

We will use bootstrap modal for create new statistics and update new statistics. we can use aid routes to create crud (create examine replace delete) software in laravel eight.we are able to use yajra datatable to list a records with pagination, sorting and filter.

I will provide you little by little manual to create ajax crud instance with laravel. you simply need to observe few step to get c.r.u.d with modals and ajax. you could effortlessly use along with your laravel mission and smooth to customise it.

Step 1: Install Laravel 8 To start with we need to get clean Laravel eight version application using bellow command, So open your terminal OR command set off and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration

In 2d step, we will make database configuration as an example database call, username, password etc for our crud utility of laravel 8. So allow's open .env report and fill all information like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Install Yajra Datatable

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle
After that you need to set providers and alias. config/app.php
.....
'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
Step 4: Create Migration Table

we are going to create ajax crud application for product. so we have to create migration for "products" table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:migration create_products_table --create=products

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.

/database/migrations/2020_01_10_102325_create_products_table.php
<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Now you have to run this migration by following command:

php artisan migrate
Step 5: Create Route

Here, we need to add resource route for product ajax crud application. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use App\Http\Controllers\ProductAjaxController;

Route::resource('ajaxproducts',ProductAjaxController::class);
Step 6: Add Controller and Model

In this step, now we should create new controller as ProductAjaxController. So run bellow command and create new controller.

So, let's copy bellow code and put on ProductAjaxController.php file.

app/Http/Controllers/ProductAjaxController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use DataTables;

class ProductAjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Product::latest()->get();
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
   
                           $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>';
   
                           $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('productAjax');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Product::updateOrCreate(['id' => $request->product_id],
                ['name' => $request->name, 'detail' => $request->detail]);        
   
        return response()->json(['success'=>'Product saved successfully.']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Product::find($id)->delete();
     
        return response()->json(['success'=>'Product deleted successfully.']);
    }
}

Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:

app/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected $fillable = [
        'name', 'detail'
    ];
}
Step 7: Add Blade Files

In last step. In this step we have to create just blade file. so we need to create only one blade file as productAjax.blade.php file.

So let's just create following file and put bellow code.

resources/views/productAjax.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax CRUD Tutorial Using Datatable </title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
</head>
<style type="text/css">
    .container{
        margin-top:150px;
    }
    h4{
        margin-bottom:30px;
    }
</style>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="row">
                <div class="col-md-12 text-center">
                    <h4>Laravel 8 Ajax CRUD Tutorial Using Datatable </h4>
                </div>
                <div class="col-md-12 text-right mb-5">
                    <a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
                </div>
                <div class="col-md-12">
                    <table class="table table-bordered data-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Name</th>
                                <th>Details</th>
                                <th width="280px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
   
<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="productForm" name="productForm" class="form-horizontal">
                    <input type="hidden" name="product_id" id="product_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                        </div>
                    </div>
     
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Details</label>
                        <div class="col-sm-12">
                            <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                        </div>
                    </div>
      
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
</body>
    
<script type="text/javascript">
    $(function () {
     
    $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('ajaxproducts.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'detail', name: 'detail'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
     
    $('#createNewProduct').click(function () {
        $('#saveBtn').val("create-product");
        $('#product_id').val('');
        $('#productForm').trigger("reset");
        $('#modelHeading').html("Create New Product");
        $('#ajaxModel').modal('show');
    });
    
    $('body').on('click', '.editProduct', function () {
        var product_id = $(this).data('id');
        $.get("{{ route('ajaxproducts.index') }}" +'/' + product_id +'/edit', function (data) {
            $('#modelHeading').html("Edit Product");
            $('#saveBtn').val("edit-user");
            $('#ajaxModel').modal('show');
            $('#product_id').val(data.id);
            $('#name').val(data.name);
            $('#detail').val(data.detail);
        })
    });
    
    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
    
        $.ajax({
            data: $('#productForm').serialize(),
            url: "{{ route('ajaxproducts.store') }}",
            type: "POST",
            dataType: 'json',
            success: function (data) {
                $('#productForm').trigger("reset");
                $('#ajaxModel').modal('hide');
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
                $('#saveBtn').html('Save Changes');
            }
        });
    });

    $('body').on('click', '.deleteProduct', function (){
        var product_id = $(this).data("id");
        var result = confirm("Are You sure want to delete !");
        if(result){
            $.ajax({
                type: "DELETE",
                url: "{{ route('ajaxproducts.store') }}"+'/'+product_id,
                success: function (data) {
                    table.draw();
                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });
        }else{
            return false;
        }
    });
});
</script>
</html>

Now you can test it by using following command:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/ajaxproducts

It will help you...