Laravel 5.5 – AppDividend https://appdividend.com Latest Code Tutorials Thu, 22 Feb 2018 14:44:02 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel 5.5 – AppDividend https://appdividend.com 32 32 Laravel Multiple Files Upload Tutorial Example From Scratch https://appdividend.com/2018/02/09/laravel-multiple-files-upload-tutorial-example/ https://appdividend.com/2018/02/09/laravel-multiple-files-upload-tutorial-example/#comments Fri, 09 Feb 2018 14:20:12 +0000 http://localhost/appdividend/?p=1627 Laravel Multiple Files Upload Tutorial With Example From Scratch

Laravel Multiple Files Upload Tutorial Example From Scratch is leading topic. We are going to build multiple files upload system using Laravel 5.5. In the frontend, We will use a jQuery plugin to populate file field and submit the more than one file to the server. It will always be excellent if you use laravel validation for your […]

The post Laravel Multiple Files Upload Tutorial Example From Scratch appeared first on AppDividend.

]]>
Laravel Multiple Files Upload Tutorial With Example From Scratch

Laravel Multiple Files Upload Tutorial Example From Scratch is leading topic. We are going to build multiple files upload system using Laravel 5.5. In the frontend, We will use a jQuery plugin to populate file field and submit the more than one file to the server. It will always be excellent if you use laravel validation for your web form in laravel project.In this tutorial, I will show you how to use laravel default validation with jQuery ajax.The server validates all the inputs against defined validation, and if any of the validation is going to fail, then it will redirect to our create page with error messages.

Programming Category (English)300x250

Laravel Multiple Files Upload Tutorial

First, we download a new copy of Laravel project by typing the following command.

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

After establishing the Laravel, configure the database. So go to the .env file and continue the database credentials.

Next, we need to create a migration file to store the images name. So go to the CMD and kicked the following command.

php artisan make:migration create_files_table

Define the schema as follows.

<?php

// create_files_table.php

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

class CreateFormsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

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

Then migrate this schema and make a table in the database.

php artisan migrate

Step 2: Define model, controller, and routes.

Hit the following command to generate model and controller.

php artisan make:model File

php artisan make:controller FileController

It will generate two files.

  1. File.php
  2. FileController.php

Now define routes in routes >> web.php file and add the following routes.

// web.php

Route::get('file','FileController@create');
Route::post('file','FileController@store');

In the FileController’s create a function, write the following code.

// FileController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('create');
    }

Immediately, make a create.blade.php file inside views folder.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  
  <div class="container">
       
    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>

</body>
</html>

Here, I have taken a natural form to add the files. We need a functionality when we can populate the input field when we click add button. So first let us do that. We have used jQuery for that feature.

Step 3: Add jQuery code to populate input field.

After adding the jQuery code and some HTML code to insert effective input fields, our file looks like this.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
   

  <div class="container">

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">

    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

</script>


</body>
</html>

Laravel 5.5 Files Upload

Step 4: Add the backend validation.

We are inserting multiple files so; we need to make array validation in our project. In a FileController.php file, add the following code to validate our input file.

// FileController.php

$this->validate($request, [

                'filename' => 'required',
                'filename.*' => 'mimes:doc,pdf,docx,zip'

]);

It validates against the required field as well file type. If the input file does not contain file or doc, pdf, docx, zip then it throws an error and laravel catch it and demonstrates these errors in the frontend. To show errors in the form, we need to write the following code after container class.

// create.blade.php

      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

Okay, so here validation is done.

Laravel Multiple Files Validation Tutorial

Step 5: Insert multiple files into the database.

After checking the validation, we need to store the file names in our database. So our final code to insert the various files in the database is following.

// FileController.php

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)

    {

        $this->validate($request, [

                'filename' => 'required',
                'filename.*' => 'mimes:doc,pdf,docx,zip'

        ]);
        
        
        if($request->hasfile('filename'))
         {

            foreach($request->file('filename') as $file)
            {
                $name=$file->getClientOriginalName();
                $file->move(public_path().'/files/', $name);  
                $data[] = $name;  
            }
         }

         $file= new File();
         $file->filename=json_encode($data);
         
        
        $file->save();

        return back()->with('success', 'Your files has been successfully added');
    }

If the input is a file, then it will loop through all the files one by one and store the file names in the array and then insert that array in the database. I am using json_encode to include the multiple file names in one row. You can make another table and then append the foreign key to that table. After success, we need to display a success message. So write that code in the create.blade.php file.

// create.blade.php

 @if(session('success'))
   <div class="alert alert-success">
      {{ session('success') }}
   </div> 
 @endif

So, our final create.blade.php file looks like this.

// create.blade.php

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

        @if(session('success'))
        <div class="alert alert-success">
          {{ session('success') }}
        </div> 
        @endif

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">


    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

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

Now, you can able to upload multiple files. Of course, images and other file formats are not allowed. Finally, our Laravel Multiple Files Upload Tutorial Example From Scratch is over.

The post Laravel Multiple Files Upload Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/02/09/laravel-multiple-files-upload-tutorial-example/feed/ 9
Laravel AJAX Tutorial Example https://appdividend.com/2018/02/07/laravel-ajax-tutorial-example/ https://appdividend.com/2018/02/07/laravel-ajax-tutorial-example/#comments Wed, 07 Feb 2018 06:26:47 +0000 http://localhost/appdividend/?p=1683 Laravel AJAX Tutorial

Laravel AJAX Tutorial Example topic. For this session, we will use Laravel 5.5. From the last three years, Laravel is PHP’s dominant framework. So many web applications are building in Laravel right now. Laravel Ecosystem is revolutionizing the PHP Web application. Until now, we have inserted the data with a page refresh. But now we will see how […]

The post Laravel AJAX Tutorial Example appeared first on AppDividend.

]]>
Laravel AJAX Tutorial

Laravel AJAX Tutorial Example topic. For this session, we will use Laravel 5.5. From the last three years, Laravel is PHP’s dominant framework. So many web applications are building in Laravel right now. Laravel Ecosystem is revolutionizing the PHP Web application. Until now, we have inserted the data with a page refresh. But now we will see how we can use AJAX request to enter the data into the database and retrieve it. If you are new to Laravel then check out my Laravel Tutorial Example From Scratch.

Introduction

AJAX is the way to communicate between client and server without page refresh. It is the technique to pass the data from one server to another server without having any interruption. Full form of AJAX is Asynchronous Javascript and XML. In the regular form, we define the post route in action but, in this case, we describe the action in Javascript and let javascript code handle the rest.

Difference between Normal and AJAX request.

The client sends a request to the server, the server responds with the particular page, and that page contains either static data or dynamic data.

While in AJAX request, a client request to the server, the server responds with the data and not the whole page. So that is the main difference between regular and ajax request. The server returns the data either in JSON format or XML format. Nowadays JSON becomes more and more popular.

Laravel 5.5 AJAX

Laravel AJAX Tutorial

We will use AJAX in Laravel 5.5. First, we will create a simple form using bootstrap. Then using jQuery, we will send a request to the server, to store the form values in the database. So let us start this small application by installing the Laravel.

Step 1: Install and configure the Laravel.

You can install the Laravel with the following command.

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

After installing the Laravel, we need to configure the database. You can set your database credentials in the .env file. We are building simple Grocery Application, where the user can add the item. So first we need to develop the schema for that. For generating migration file, we need to type the following command.

php artisan make:migration create_groceries_table

So it has generated the migration file, now define the columns in that file.

public function up()
 {
   Schema::create('groceries', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');
      $table->string('type');
      $table->integer('price');
      $table->timestamps();
    });
 }

Now migrate the table into our database.

php artisan migrate

Step 2: Define routes, model and controllers.

To generate model and controller, hit the following commands.

php artisan make:model Grocery
php artisan make:controller GroceryController

Next step is to define the routes. We need to add the routes in the routes  >>  web.php file.

// web.php

Route::view('/grocery', 'grocery');
Route::post('/grocery/post', 'GroceryController@store');

Till now, we have not created any view file. So let us do that. We need to create this file inside resources  >>  views  >>  grocery.blade.php file.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <title>Grocery Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
      Grocery App
    </body>
</html>

Go to the cmd and start the development server.

php artisan serve

Navigate to http://localhost:8000/grocery You can see our grocery page in the browser.

Step 3: Create a bootstrap form.

In the grocery.blade.php file, write the following bootstrap code.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <title>Grocery Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
      <div class="container">
         <form id="myForm">
            <div class="form-group">
              <label for="name">Name:</label>
              <input type="text" class="form-control" id="name">
            </div>
            <div class="form-group">
              <label for="type">Type:</label>
              <input type="text" class="form-control" id="type">
            </div>
            <div class="form-group">
               <label for="price">Price:</label>
               <input type="text" class="form-control" id="price">
             </div>
            <button class="btn btn-primary">Submit</button>
          </form>
      </div>
    </body>
</html>

Okay, now add a jQuery in the grocery.blade.php file. Remeber that you need to add the JS files just above the closing body tag. I have used CDN for jQuery. You can use your local jQuery file.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
</script>

Step 4: Setup an Ajax request for Laravel.

First, we need to define the CSRF token in our meta tag. In previous cases, we describe the field called “{{ csrf_field() }},” but in our ajax case, we have defined in the meta tag. When we set up an ajax request, we also need to setup header for our csrf token. When we post the data to the server, it needs to contain CSRF token.

 jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
            });
          });

So, when the user clicks the submit button, this click event is called, and then first we prevent the form to send and then set the headers for our future post request.

Now, Add the jQuery.ajax() function in that click event to submit the request to the server with all the three inputs data.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous">
</script>
<script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/grocery/post') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     type: jQuery('#type').val(),
                     price: jQuery('#price').val()
                  },
                  success: function(result){
                     console.log(result);
                  }});
               });
            });
</script>

jQuery.ajax() function contains an object of parameters. It contains URL to send the request, method property to check which HTTP request method is used, a data object that contains all the form data. The success and error function is there. If our request sends successfully then, we can catch the returned data in the success function, and if it throws an error, then we can catch the error in the error function.

Step 5: Write the store function to store the data.

Switch to the GroceryController.php file and add the following code.

// GroceryController.php

use App\Grocery;

 public function store(Request $request)
 {
        $grocery = new Grocery();
        $grocery->name = $request->name;
        $grocery->type = $request->type;
        $grocery->price = $request->price;

        $grocery->save();
        return response()->json(['success'=>'Data is successfully added']);
 }

Now, we need to display the message that we have successfully added the data.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <meta name="_token" content="{{csrf_token()}}" />
        <title>Grocery Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
      <div class="container">
         <div class="alert alert-success" style="display:none"></div>
         <form id="myForm">
            <div class="form-group">
              <label for="name">Name:</label>
              <input type="text" class="form-control" id="name">
            </div>
            <div class="form-group">
              <label for="type">Type:</label>
              <input type="text" class="form-control" id="type">
            </div>
            <div class="form-group">
               <label for="price">Price:</label>
               <input type="text" class="form-control" id="price">
             </div>
            <button class="btn btn-primary" id="ajaxSubmit">Submit</button>
          </form>
      </div>
      <script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
      </script>
      <script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/grocery/post') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     type: jQuery('#type').val(),
                     price: jQuery('#price').val()
                  },
                  success: function(result){
                     jQuery('.alert').show();
                     jQuery('.alert').html(result.success);
                  }});
               });
            });
      </script>
    </body>
</html>

So, here on success, I have displayed the message that data has been successfully added.

Finally, Our Laravel AJAX Tutorial with an example is over.

 

The post Laravel AJAX Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/02/07/laravel-ajax-tutorial-example/feed/ 21
Laravel Multiple Images Upload Tutorial Example From Scratch https://appdividend.com/2018/02/05/laravel-multiple-images-upload-tutorial/ https://appdividend.com/2018/02/05/laravel-multiple-images-upload-tutorial/#comments Mon, 05 Feb 2018 22:12:22 +0000 http://localhost/appdividend/?p=1609 Laravel Multiple Images Upload Tutorial Example From Scratch

Laravel Multiple Images Upload Tutorial Example From Scratch is today’s leading topic. We will build a simple multiple images upload system using Laravel 5.5. We will use a jQuery plugin to populate image field and submit the multiple images to the server. The server checks all the inputs against defined validation, and if any of the […]

The post Laravel Multiple Images Upload Tutorial Example From Scratch appeared first on AppDividend.

]]>
Laravel Multiple Images Upload Tutorial Example From Scratch

Laravel Multiple Images Upload Tutorial Example From Scratch is today’s leading topic. We will build a simple multiple images upload system using Laravel 5.5. We will use a jQuery plugin to populate image field and submit the multiple images to the server. The server checks all the inputs against defined validation, and if any of the validation fails, it will redirect to our create page with error messages.

Laravel Multiple Images Upload Tutorial

First, we download a fresh copy of Laravel project by typing the following command.

Step 1: Configure Laravel.

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

After installing the Laravel, configure the database. So go to the .env file and add the database credentials.

Then we need to create a migration file to store the images name. So go to the CMD and hit the following command.

php artisan make:migration create_forms_table

Define the schema as follows.

<?php

// create_forms_table.php

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

class CreateFormsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('forms', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

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

Next step will be to migrate this schema and make a table in the database.

php artisan migrate

Now, we need to setup controller and model file for our application. Type the following command to generate model and controller.

php artisan make:model Form

php artisan make:controller FormController

It will generate two files.

  1. Form.php
  2. FormController.php

Step 2: Define routes in the web.php file.

Go to the routes  >>  web.php file and add the following routes.

// web.php

Route::get('form','FormController@create');
Route::post('form','FormController@store');

In the FormController’s create a function, write the following code.

// FormController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('create');
    }

Now, let us make a create.blade.php file inside views folder.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  
  <div class="container">
       
    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>

</body>
</html>

Here, I have taken a straightforward form to add the images. We need a functionality when we can populate the input field when we click add button. So first let us do that. We have used jQuery for that feature.

Step 3: Add jQuery code to populate input field.

After adding the jQuery code and some HTML code to insert dynamic input fields, our file looks like this.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
   

  <div class="container">

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">

    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

</script>


</body>
</html>

Step 5: Add the backend validation.

We are inserting multiple images so; we need to make array validation in our project. In a FormController.php file, add the following code to validate our input file.

// FormController.php

$this->validate($request, [
    'filename' => 'required',
    'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);

It checks against the required field as well image type. If the input file does not contain image or jpg, png ,gif or svg then it throws an error and laravel catch it and display these errors in the frontend. To show errors in the form, we need to write the following code after container class.

// create.blade.php

      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

Okay, so here validation is done.

jQuery Dynamic Fields

Step 6: Insert multiple images in the database.

After checking the validation, we need to store the image names in our database. So our final code to insert the various images on the database is following.

// FormController.php

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)

    {

        $this->validate($request, [

                'filename' => 'required',
                'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

        ]);
        
        if($request->hasfile('filename'))
         {

            foreach($request->file('filename') as $image)
            {
                $name=$image->getClientOriginalName();
                $image->move(public_path().'/images/', $name);  
                $data[] = $name;  
            }
         }

         $form= new Form();
         $form->filename=json_encode($data);
         
        
        $form->save();

        return back()->with('success', 'Your images has been successfully');
    }

If the input file is image then it will loop through all the images one by one and store the image names in the array and then insert that array in the database. I am using json_encode to insert the multiple image names in one row. You can make another table and then add the foreign key to that table. After success, we need to display a success message. So write that code in the create.blade.php file.

// create.blade.php

 @if(session('success'))
   <div class="alert alert-success">
      {{ session('success') }}
   </div> 
 @endif

So, our final create.blade.php file looks like this.

// create.blade.php

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

        @if(session('success'))
        <div class="alert alert-success">
          {{ session('success') }}
        </div> 
        @endif

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">


    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

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

I have already put this code on Github.

Github Repository

The post Laravel Multiple Images Upload Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/02/05/laravel-multiple-images-upload-tutorial/feed/ 29
Laravel Queues Tutorial With Example From Scratch https://appdividend.com/2017/12/21/laravel-queues-tutorial-example-scratch/ https://appdividend.com/2017/12/21/laravel-queues-tutorial-example-scratch/#comments Thu, 21 Dec 2017 12:30:32 +0000 http://localhost/appdividend/?p=1455 Laravel Queues Tutorial With Example From Scratch

Laravel Queues Tutorial With Example From Scratch is today’s leading topic. Laravel 5.5 queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer the processing of a time-consuming task, such as sending an email. Delaying these time-consuming tasks […]

The post Laravel Queues Tutorial With Example From Scratch appeared first on AppDividend.

]]>
Laravel Queues Tutorial With Example From Scratch

Laravel Queues Tutorial With Example From Scratch is today’s leading topic. Laravel 5.5 queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer the processing of a time-consuming task, such as sending an email. Delaying these time-consuming tasks drastically speeds up web requests to your application.

The queue configuration file is stored in.config/queue.php In this file, you will find connection configurations for each of the queue drivers that are included with the framework, which consists of a database, BeanstalkdAmazon SQSRedis, and synchronous driver that will execute jobs immediately (for local use). A null queue driver is also included which simply discards queued jobs.

Laravel Queue Send Email Example

Sending an email is a time-consuming task, so what we will do is, we will create a job that’s the only task is to send an email to the user in the background. So let us get started.

Step 1: Configure the Laravel

Install it by the following command.

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

Now, in the .env file, configure the database and email server.

For email sending, I have used https://mailtrap.io. So if you want that use, go to the website and signup, and you will see your username and password, grab it and put in the .env file, and you are good to go.

Also, we need to change the queue driver to the database. By default laravel uses sync.

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:N/+b/PAQXgtG8OiYu3TKyudhicgYsGYfb551yrqkjmQ=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

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

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=database

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

Step 2: Create a route for sending mail.

We will create one route to send an email and also create one controller called EmailController.

php artisan make:controller EmailController

In routes >> web.php file, add the following code.

Route::get('email', 'EmailController@sendEmail');

Okay, now we need to create one mailable class, so in the terminal, type the following command.

php artisan make:mail SendMailable

So, it will create this file inside App\Mail\SendMailable.php.

Now, write the sendMail function inside the MailController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;

class EmailController extends Controller
{
    public function sendEmail()
    {
        Mail::to('mail@appdividend.com')->send(new SendMailable());
        echo 'email sent';
    }
}

Also, out SendMailable.php file looks like this.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMailable extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('welcome');
    }
}

Now, start the server with the following command.

php artisan serve

Switch to the browser and hit this URL: http://localhost:8000/email

You will see, there is a delay and then we can get the mail. So here is the solution and that is a queue.

Step 3: Configure Queue.

We can use queue with the Database, Redis, and other drivers as mentioned  in Laravel 5.5 Queues.

We will use Database and so we need to create a migration for Jobs table.

php artisan queue:table

It will create a migration and then we need to migrate the database.

php artisan migrate

It will create the jobs table in the database.

Step 4: Create a job

Now, we will need to create the job that purpose is to send the actual email to the user.

php artisan make:job SendEmailJob

Now, the send email function will reside in the job file. So that job file looks like this.

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;

class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to('mail@appdividend.com')->send(new SendMailable());
    }
}

In EmailController.php file, we will need to trigger this job.

So we need to dispatch the newly created job from the EmailController. So that code will look like this.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Jobs\SendEmailJob;

class EmailController extends Controller
{
    public function sendEmail()
    {
        dispatch(new SendEmailJob());

        echo 'email sent';
    }
}

Now, again hit that email URL.

Still, the delay is there; we have just moved the logic to the job file. We need to send the mail in the background. So we need to delay our queue.

public function sendEmail()
{
   $emailJob = (new SendEmailJob())->delay(Carbon::now()->addSeconds(3));
   dispatch($emailJob);

   echo 'email sent';
}

Now, hit the URL again.

This time there is only 3 seconds delay, or we can say no delay, but wait, if you switch to mailtrap then there is no mail either. So how we can send real mail also.

Go to the database and see the jobs table. There is one entry for the job. So that means, the process of that job is not started. So Laravel, there is a concept called Queue Worker. We need to run that Queue Worker.

Switch to the terminal and type the following command to start the queue worker.

php artisan queue:work

In the terminal, it will say like this.

[2017-12-21 13:58:14] Processing: App\Jobs\SendEmailJob
[2017-12-21 13:58:19] Processed:  App\Jobs\SendEmailJob

Now, go to the mailtrap, and yes we will see that mail sent.

Again refresh this URL.

It will say the email sent and after 5-6 seconds mail also sent to the mailtrap.

We can create as many jobs as we want but make sure that the queue worker is started and all the configurations are correctly set.

Bingo, our Laravel Queues Tutorial  is over.

The post Laravel Queues Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/12/21/laravel-queues-tutorial-example-scratch/feed/ 9
Laravel Gates Tutorial Example From Scratch https://appdividend.com/2017/12/13/laravel-gates-tutorial-example-scratch/ https://appdividend.com/2017/12/13/laravel-gates-tutorial-example-scratch/#comments Wed, 13 Dec 2017 12:06:13 +0000 http://localhost/appdividend/?p=1446 Gates In Laravel

Laravel Gates Tutorial Example From Scratch is today’s main topic. Gates and Policies restrict the users based on their logic. Gates may also be defined using a Class@method style callback string, like controllers. Writing Gates Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the class App\Providers\AuthServiceProvider using the facade  […]

The post Laravel Gates Tutorial Example From Scratch appeared first on AppDividend.

]]>
Gates In Laravel

Laravel Gates Tutorial Example From Scratch is today’s main topic. Gates and Policies restrict the users based on their logic. Gates may also be defined using a Class@method style callback string, like controllers.

Writing Gates

Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the class App\Providers\AuthServiceProvider using the facade  Gate. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model.

Laravel Gates Tutorial

Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We’ll explore gates first and then examine policies.

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', 'PostPolicy@update');
}

Now, we will take an example, to understand the Gates. Laravel provides user table’s migration by default, so what we will do is that make one more column called isAdmin and set the datatype to the boolean.

Step 1: Install Laravel And Setup Database.

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

Now, set up the database in a .env file.

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

We need to change the user migration file and add one more column called isAdmin as a boolean.

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

Now, migrate the database.

php artisan migrate

Step 2: Make auth system

In your root, type the following command in your terminal.

php artisan make:auth

It will create the register and login system for us. Now, register the three users for the sample.

Now, go to the table and change any of the user’s isAdmin value to 1. This is an example, so we manually do it otherwise we need to change it to 1 programmatically.

gates in laravel 5.5

 

So, we will write the gates logic for a user, who is the admin. Otherwise, some resources will not be displayed to the logged in user, if he is not an admin.

Now, go to the resources  >>  views  >>  welcome.blade.php. Add the following line to the code.

@if (Route::has('login'))
<div class="top-right links">
  @auth
  <a href="{{ url('/home') }}">Home</a>
  <a href="{{ url('/private') }}">Private</a>
  @else
  <a href="{{ route('login') }}">Login</a>
  <a href="{{ route('register') }}">Register</a>
  @endauth
</div>
@endif

Also, define the route in the routes  >>  web.php file.

Route::get('/privare', 'HomeController@private')->name('private');
/**
  * Show the application private resources.
  *
  * @return \Illuminate\Http\Response
  */
   public function private()
   {
       return view('private');
   }

Now, create private.blade.php file.

@extends('layouts.app')

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

                <div class="panel-body">
                    Confidential Information
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, log in to the application and go to the http://localhost:8000

You can see another navigation item called Private. Right now, you can see this thing, and you can navigate to that page. But we need to prevent viewing this page which is not an admin. That is why Gates come into the play.

Step 3: Define the Gates.

Go to the app  >>  providers  >>  AuthServiceProvider.php file and define the gate.

   /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('admin-only', function ($user) {
            if($user->isAdmin == 1)
            {
                return true;
            }
            return false;
        });
    }

Okay, so now remaining step is to tell the application that this route is protected to the admin.

So in HomeController file, write the following code.

   use Illuminate\Support\Facades\Gate;

   /**
     * Show the application private resources.
     *
     * @return \Illuminate\Http\Response
     */
    public function private()
    {
        if (Gate::allows('admin-only', auth()->user())) {
            return view('private');
        }
        return 'You are not admin!!!!';
    }

So, when you logged in as a user, whose isAdmin is one then, you can view the private resources, otherwise not. Next step is to do not display private navigation item to the non-admin user because it makes no sense to show them the secret part at all.

In the welcome.blade.php file, you can add the @can directive.

@if (Route::has('login'))
<div class="top-right links">
  @auth
   <a href="{{ url('/home') }}">Home</a>
   @can('admin-only', auth()->user())
    <a href="{{ url('/private') }}">Private</a>
   @endcan
  @else
   <a href="{{ route('login') }}">Login</a>
   <a href="{{ route('register') }}">Register</a>
  @endauth
</div>
@endif

Now, only admin can see the Private view of the application. So we have used Gate as an authorized user to show only resources that user has been allowed. There is one more concept called Policy, which we will see in the next tutorial. You can explore more API in Laravel’s documentation.

That is it for the Laravel Gates Tutorial Example From Scratch. 

The post Laravel Gates Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/12/13/laravel-gates-tutorial-example-scratch/feed/ 4
Laravel 5.5 Facades Tutorial https://appdividend.com/2017/12/02/laravel-5-5-facades-tutorial/ https://appdividend.com/2017/12/02/laravel-5-5-facades-tutorial/#comments Sat, 02 Dec 2017 09:42:07 +0000 http://localhost/appdividend/?p=1437 Laravel 5.5 Facades Tutorial

Laravel 5.5 Facades Tutorial is today’s leading topic. Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with so many facades which provide access to almost all of the Laravel’s features. Laravel facade serves as “static proxies” to underlying classes in the service container. All of Laravel’s facades are defined […]

The post Laravel 5.5 Facades Tutorial appeared first on AppDividend.

]]>
Laravel 5.5 Facades Tutorial

Laravel 5.5 Facades Tutorial is today’s leading topic. Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with so many facades which provide access to almost all of the Laravel’s features. Laravel facade serves as “static proxies” to underlying classes in the service container. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});

Laravel 5.5 Facades

Now, we will take one example to illustrate the Laravel Facade. First, download the Fresh Laravel. In app directory, make one folder called Person. In that folder, create one file called Person.php.

<?php

// Person.php

namespace App\Person;

class Person
{
    public function getName()
    {
        return 'AppDividend';
    }
}

To call this method, we just need to include this file in the routes  >>  web.php file.

<?php

// web.php

use App\Person\Person;

Route::get('/', function () {
    $person = new Person();
    echo $person->getName();
});

So, here in this example, Person.php file has one non-static method. So, we have made one object of it and then call the method, and we can see the output in the browser.

Now, change the code like this in the web.php file.

<?php

// web.php

Route::get('/', function () {
    Person::getName();
});

Run this in the browser, you will see like this.

Class ‘Person’ not found.”

So, if you still want the output result like “AppDividend,” then you have to use the Power of Facades.

Facades

In the app directory, create one more folder called, Facades and in that folder, make one file called Person.php.

<?php

namespace App\Facades;

class Person extends \Illuminate\Support\Facades\Facade
{
    public static function getFacadeAccessor()
    {
        return 'name';
    }
}

Now, we need to map this accessor to our original Person\Person.php class and make its object. That is where service container is required. We can though write this logic in web.php, or we can create one file called NameServiceProvider. For this example, we will write this logic in the web.php file.

<?php

// web.php

app()->bind('name', function() {
    return new \App\Person\Person;
});

Route::get('/', function () {
    return Person::getName();
});

Here, we are binding the facade accessor to the original class, on which we need to create an object. So behind the scenes, we are newing up the instance and call its method.

Also, we need to add aliases in the config  >> app.php file.

// app.php

'aliases' => [
   'Person' => App\Facades\Person::class,
]

Now, again hit the following URL: http://localhost:8000/

You will see the “AppDividend” as an output. So we have achieved the goal of calling that method, which looks like static but behind the scenes, we are creating the object and call the method with that object. Laravel provides almost every service with the help of the Facade pattern. That makes it unique from the other PHP Framework.

So, that is it. Laravel 5.5 Facades Tutorial here is over.

The post Laravel 5.5 Facades Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2017/12/02/laravel-5-5-facades-tutorial/feed/ 3
How To Integrate Datatables API In Laravel 5.5 https://appdividend.com/2017/11/29/integrate-datatables-api-laravel-5-5/ https://appdividend.com/2017/11/29/integrate-datatables-api-laravel-5-5/#respond Wed, 29 Nov 2017 22:55:53 +0000 http://localhost/appdividend/?p=1432 How To Integrate Datatables API In Laravel 5.5 Tutorial

How To Integrate Datatables API In Laravel 5.5 Tutorial using Javascript Library is today’s leading topic. If we want to list the data from the database then sorting, searching and pagination is the basic functionality, we want to use. There is also one package available in the Laravel to use Datatables, but we will use JS to integrate […]

The post How To Integrate Datatables API In Laravel 5.5 appeared first on AppDividend.

]]>
How To Integrate Datatables API In Laravel 5.5 Tutorial

How To Integrate Datatables API In Laravel 5.5 Tutorial using Javascript Library is today’s leading topic. If we want to list the data from the database then sorting, searching and pagination is the basic functionality, we want to use. There is also one package available in the Laravel to use Datatables, but we will use JS to integrate into our tables.

How To Integrate Datatables API In Laravel 5.5

First, we will install the Laravel as well as Install the AdminLTE theme. If you do not know, how to integrate the admin template in Laravel, then check out my How To Integrate Admin Template Into Laravel 5.5.

Step 1: Install Laravel 5.5.

Type the following command.

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

After installation, edit the .env file and setup the database. Now, define the route for the admin template.

Route::view('admin', 'home');

Now, we need to create one master template file, which is inherited by all of its child pages.

In the resources  >>  views folder, make one file called master.blade.php.

Step 2: Make a layout file called master.blade.php

In this file, we will include all the css and js files, which will be needed in all the pages.

Now, make one folder inside views directory, called partials. In that folder, we will put our header and sidebar files. Our master.blade.php file looks like this.

<!-- master.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}" />
    <link rel="stylesheet" href="{{asset('css/AdminLTE.min.css')}}" />
    <link rel="stylesheet" href="{{asset('css/skins/_all-skins.min.css')}}" />
    <link rel="stylesheet" href="{{asset('font-awesome/css/font-awesome.min.css')}}" />
    @yield('stylesheets')
</head>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        @include('partials.header')
        @include('partials.sidebar')
        @yield('content')
    </div>
    <script src="{{ asset('js/jquery/dist/jquery.min.js') }}"></script>
    <script src="{{ asset('js/bootstrap/dist/js/bootstrap.min.js') }}"></script>
    <script src="{{ asset('js/adminlte.min.js') }}"></script>
    @yield('scripts')
</body>
</html>

This file includes required CSS and JS that will run the theme smoothly throughout the project.

Our header.js file looks like this.

<!-- header.blade.php -->

<header class="main-header">
    <a href="" class="logo">
        <span class="logo-mini"><b>A</b>LT</span>
        <span class="logo-lg"><b>Admin</b>LTE</span>
    </a>
    <nav class="navbar navbar-static-top">
        <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
            <span class="sr-only">Toggle navigation</span>
        </a>
        <div class="navbar-custom-menu">
            <ul class="nav navbar-nav">
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <img src="{{asset('img/user2-160x160.jpg')}}" class="user-image" alt="User Image" />
                        <span class="hidden-xs">AppDividend</span>
                    </a>
                    <ul class="dropdown-menu">
                    <!-- User image -->
                        <li class="user-header">
                            <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
                            <p>
                                AppDividend
                            </p>
                        </li>
                        <li class="user-footer">
                            <div class="pull-right">
                                <a href="" class="btn btn-default">Sign out</a>
                            </div>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
</header>

Also, sidebar.blade.php file looks like this.

<!-- sidebar.blade.php -->

<aside class="main-sidebar">
    <section class="sidebar">    
        <div class="user-panel">
            <div class="pull-left image">
                <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
            </div>
            <div class="pull-left info">
                <p>AppDividend</p>
            </div>
        </div>
        <ul class="sidebar-menu" data-widget="tree">
            <li class="treeview">
                <a href="#">
                    <i class="fa fa-dashboard"></i> <span>Categories</span>
                    <span class="pull-right-container">
                    <i class="fa fa-angle-left pull-right"></i>
                    </span>
                </a>
                <ul class="treeview-menu">
                    <li><a href=""><i class="fa fa-circle-o"></i>Add Category</a></li>
                    <li><a href=""><i class="fa fa-circle-o"></i>All Categories</a></li>
                </ul>
            </li> 
        </ul>
    </section>
</aside>

Now, if you have included the proper css and js files, then hit the following URL in the browser. http://localhost:8000/admin

Step 3: Make model, migration, and controller.

You will see the working admin panel. Now, we need to create one model and migration file to make the table.

php artisan make:model Item -m

Also, create one controller file.

php artisan make:controller ItemController

Now, enter the following schema into the migrations.

<?php

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

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

Next, migrate the tables into the database via the following command.

php artisan migrate

Now, create one seeder file, to seed the data into the database.

php artisan make:seeder ItemTableSeeder

We will use model factories to populate the database. So let’s define the schema for the ItemTableSeeder.

Go to the database >> factories  >> UserFactory.php and define one more factory.

<?php

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Item::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'price' => $faker->randomDigit,
    ];
});

Create the factory. Go to the newly created ItemTableSeeder.php file.

<?php

use Illuminate\Database\Seeder;

class ItemTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Item::class, 100)->create();
    }
}

Now, go to the DatabaseSeeder.php file.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ItemTableSeeder::class);
    }
}

Run the following command in your terminal.

php artisan db:seed

It will create 100 rows in the table, and if you find an error in the terminal like class not found then, please hit the following command.

composer dump-autoload

Step 4: Create index() function.

We need to create the index function inside the ItemController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ItemController extends Controller
{
    public function index()
    {
        $items = \App\Item::all();

        return view('home', compact('items'));
    }
}

Your web.php file looks like this.

Route::get('admin', 'ItemController@index');
<!-- home.blade.php -->

@extends('master')

@section('content')
    <div class="content-wrapper">
        <section class="content-header">
            <h1>
                Dashboard
                <small>Control panel</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                <li class="active">Dashboard</li>
            </ol>
        </section>
        <section class="content">
            <div class="row">
                <table id="pageTable" class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Price</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach ($items as $item)
                        <tr>
                            <td>
                                {{ $item->id }}
                            </td>
                            <td>
                                {{ $item->name }}
                            </td>
                            <td>
                                {{ $item->price }}
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </section>
    </div>
@endsection
@section('scripts')
    <script src="{{ asset('js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('js/jquery.dataTables.bootstrap.min.js') }}"></script>
    <script>
         jQuery(function($) {
        //initiate dataTables plugin
        var myTable = 
        $('#pageTable')
        //.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
        .DataTable( {
            bAutoWidth: false,
            "aoColumns": [
                null,
                null,
                null
            ],
            "aaSorting": [],
            
            
            //"bProcessing": true,
            //"bServerSide": true,
            //"sAjaxSource": "http://127.0.0.1/table.php"   ,
    
            //,
            //"sScrollY": "200px",
            //"bPaginate": false,
    
            //"sScrollX": "100%",
            //"sScrollXInner": "120%",
            //"bScrollCollapse": true,
            //Note: if you are applying horizontal scrolling (sScrollX) on a ".table-bordered"
            //you may want to wrap the table inside a "div.dataTables_borderWrap" element
    
            //"iDisplayLength": 50
    
    
                select: {
                    style: 'multi'
                }
            });
        });
    </script>
@endsection

Now, you can hit this URL: http://localhost:8000/admin

Laravel Datatables

 

Finally, our How To Integrate Datatables API In Laravel 5.5 Tutorial is over.

 

 

 

The post How To Integrate Datatables API In Laravel 5.5 appeared first on AppDividend.

]]>
https://appdividend.com/2017/11/29/integrate-datatables-api-laravel-5-5/feed/ 0
How To Integrate Admin Template In Laravel 5.5 https://appdividend.com/2017/11/28/integrate-admin-template-laravel-5-5/ https://appdividend.com/2017/11/28/integrate-admin-template-laravel-5-5/#comments Tue, 28 Nov 2017 21:05:04 +0000 http://localhost/appdividend/?p=1426 Integrate Admin Template in Laravel 5.5

How to integrate admin template in Laravel 5.5 is today’s leading topic. If you are building a web application, then admin panel is the most used web part. So in today’s tutorial, I will show you how to integrate any admin panel easily with the Laravel. We will do it from scratch. We will use AdminLTE. […]

The post How To Integrate Admin Template In Laravel 5.5 appeared first on AppDividend.

]]>
Integrate Admin Template in Laravel 5.5

How to integrate admin template in Laravel 5.5 is today’s leading topic. If you are building a web application, then admin panel is the most used web part. So in today’s tutorial, I will show you how to integrate any admin panel easily with the Laravel. We will do it from scratch. We will use AdminLTE.

Integrate admin template in Laravel 5.5

First, we will download the admin panel template in the plain HTML, and then we will download the Laravel 5.5.

Step 1: Install the Laravel 5.5

Type the following command.

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

After installation, edit the .env file and setup the database. Now, define the route for the admin template.

Route::view('admin', 'home');

Now, we need to create one master template file, which is inherited by all of its child pages.

In the resources  >>  views folder, make one file called master.blade.php.

Step 2: Make a layout file called master.blade.php

In this file, we will include all the css and js files, which will be needed in all the pages.

Now, make one folder inside views directory, called partials. In that folder, we will put our header and sidebar files. Our master.blade.php file looks like this.

<!-- master.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}" />
    <link rel="stylesheet" href="{{asset('css/AdminLTE.min.css')}}" />
    <link rel="stylesheet" href="{{asset('css/skins/_all-skins.min.css')}}" />
    <link rel="stylesheet" href="{{asset('font-awesome/css/font-awesome.min.css')}}" />
    @yield('stylesheets')
</head>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        @include('partials.header')
        @include('partials.sidebar')
        @yield('content')
    </div>
    <script src="{{ asset('js/jquery/dist/jquery.min.js') }}"></script>
    <script src="{{ asset('js/bootstrap/dist/js/bootstrap.min.js') }}"></script>
    <script src="{{ asset('js/adminlte.min.js') }}"></script>
    @yield('scripts')
</body>
</html>

This file includes required CSS and JS that will run the theme smoothly throughout the project.

Our header.js file looks like this.

<!-- header.blade.php -->

<header class="main-header">
    <a href="" class="logo">
        <span class="logo-mini"><b>A</b>LT</span>
        <span class="logo-lg"><b>Admin</b>LTE</span>
    </a>
    <nav class="navbar navbar-static-top">
        <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
            <span class="sr-only">Toggle navigation</span>
        </a>
        <div class="navbar-custom-menu">
            <ul class="nav navbar-nav">
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <img src="{{asset('img/user2-160x160.jpg')}}" class="user-image" alt="User Image" />
                        <span class="hidden-xs">AppDividend</span>
                    </a>
                    <ul class="dropdown-menu">
                    <!-- User image -->
                        <li class="user-header">
                            <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
                            <p>
                                AppDividend
                            </p>
                        </li>
                        <li class="user-footer">
                            <div class="pull-right">
                                <a href="" class="btn btn-default">Sign out</a>
                            </div>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
</header>

Also, sidebar.blade.php file looks like this.

<!-- sidebar.blade.php -->

<aside class="main-sidebar">
    <section class="sidebar">    
        <div class="user-panel">
            <div class="pull-left image">
                <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
            </div>
            <div class="pull-left info">
                <p>AppDividend</p>
            </div>
        </div>
        <ul class="sidebar-menu" data-widget="tree">
            <li class="treeview">
                <a href="#">
                    <i class="fa fa-dashboard"></i> <span>Categories</span>
                    <span class="pull-right-container">
                    <i class="fa fa-angle-left pull-right"></i>
                    </span>
                </a>
                <ul class="treeview-menu">
                    <li><a href=""><i class="fa fa-circle-o"></i>Add Category</a></li>
                    <li><a href=""><i class="fa fa-circle-o"></i>All Categories</a></li>
                </ul>
            </li> 
        </ul>
    </section>
</aside>

Now, if you have included the proper css and js files, then hit the following URL in the browser.

http://localhost:8000/admin

Remeber, you need to start the laravel development server.

Conclusion

You can further modify the theme by dividing into smaller dynamic pieces as per your requirement. This is just a demo. Our theme looks like this.

 

adminlte laravel

The post How To Integrate Admin Template In Laravel 5.5 appeared first on AppDividend.

]]>
https://appdividend.com/2017/11/28/integrate-admin-template-laravel-5-5/feed/ 11
Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch https://appdividend.com/2017/10/15/laravel-5-5-crud-example-tutorial/ https://appdividend.com/2017/10/15/laravel-5-5-crud-example-tutorial/#comments Sun, 15 Oct 2017 16:57:20 +0000 http://localhost/appdividend/?p=1157 Laravel 5.5 CRUD Example Step By Step From Scratch

Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch is today’s leading topic. We are going to make Ticket System Project In Laravel 5.5. So let us get started. Laravel 5.5 CRUD Tutorial First of all, we will make one Laravel Project and then step by step; we will build this project. Ticket System is ultimately […]

The post Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch appeared first on AppDividend.

]]>
Laravel 5.5 CRUD Example Step By Step From Scratch

Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch is today’s leading topic. We are going to make Ticket System Project In Laravel 5.5. So let us get started.

Laravel 5.5 CRUD Tutorial

First of all, we will make one Laravel Project and then step by step; we will build this project. Ticket System is ultimately a Laravel 5.5 CRUD Operations, that is why my focus is on Laravel CRUD.

Step 1: Configure Laravel 5.5 Project.

Install the brand new Laravel Project by the typing following command.

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

Next, configure the database in the .env file.

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

Okay, now we need to make one schema for the database.

Now, this is Ticket’s table schema.

<?php

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

class CreateTicketsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tickets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
    }

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

Run the following command.

php artisan migrate

It will create the tables in the database.

Step 2: Laravel Authentication.

Laravel 5.5 Provides us Authentication out of the box. Just type the following command.

php artisan make:auth

Start the Laravel server by the following command.

php artisan serve

We can register the user by the following URL: http://localhost:8000/register

 

Step 3: Make models and controllers for our application.

We need to make TicketController.

Type the following cmd in the terminal.

php artisan make:controller TicketController

Also, make the models for the same. The User model is already there, so no need to create again.

php artisan make:model Ticket

Step 4: Create the views for our application.

Make one user folder and in that make one file called create.blade.php.

@extends('layouts.app')

@section('content')
<div class="container">
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div><br />
@endif
    <div class="row">
    <form method="post" action="{{url('/create/ticket')}}">
        <div class="form-group">
            <input type="hidden" value="{{csrf_token()}}" name="_token" />
            <label for="title">Ticket Title:</label>
            <input type="text" class="form-control" name="title"/>
        </div>
        <div class="form-group">
            <label for="description">Ticket Description:</label>
            <textarea cols="5" rows="5" class="form-control" name="description"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create</button>
        </form>
    </div>
</div>
@endsection

Now, make a route to get this file.

Route::get('/create/ticket','TicketController@create');

Also, write the controller get function.

/**
  * Show the form for creating a new resource.
  *
  * @return \Illuminate\Http\Response
  */
public function create()
{
   return view('user.create');
}

To store the data in a database, first, we need to prevent the mass assignment exception.

So, in the Ticket.php model, add the following attribute.

protected $fillable = ['user_id', 'title', 'description'];

Create one web route to handle the post request.

Route::post('/create/ticket','TicketController@store');

Include Ticket.php model into the TicketController.php file and write the store function code.

use App\Ticket;

 /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $ticket = new Ticket();
        $data = $this->validate($request, [
            'description'=>'required',
            'title'=> 'required'
        ]);
       
        $ticket->saveTicket($data);
        return redirect('/home')->with('success', 'New support ticket has been created! Wait sometime to get resolved');
    }

Also, we have created the saveTicket() function into the model.

public function saveTicket($data)
{
        $this->user_id = auth()->user()->id;
        $this->title = $data['title'];
        $this->description = $data['description'];
        $this->save();
        return 1;
}

Step 5: Display the tickets.

In the home.blade.php file, write the following code.

@extends('layouts.app')

@section('content')
<div class="container">
    @if(\Session::has('success'))
        <div class="alert alert-success">
            {{\Session::get('success')}}
        </div>
    @endif
   
    <div class="row">
       <a href="{{url('/create/ticket')}}" class="btn btn-success">Create Ticket</a>
       <a href="{{url('/tickets')}}" class="btn btn-default">All Tickets</a>
    </div>
</div>
@endsection

Make one route for the listing of the tickets.

Route::get('/tickets', 'TicketController@index');
/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tickets = Ticket::where('user_id', auth()->user()->id)->get();
        
        return view('user.index',compact('tickets'));
    }

Create one index.blade.php file inside user folder.

@extends('layouts.app')

@section('content')
<div class="container">
    <table class="table table-striped">
        <thead>
            <tr>
              <td>ID</td>
              <td>Title</td>
              <td>Description</td>
              <td colspan="2">Action</td>
            </tr>
        </thead>
        <tbody>
            @foreach($tickets as $ticket)
            <tr>
                <td>{{$ticket->id}}</td>
                <td>{{$ticket->title}}</td>
                <td>{{$ticket->description}}</td>
                <td>Edit</td>
                <td>Delete</td>
            </tr>
            @endforeach
        </tbody>
    </table>
<div>
@endsection

Step 6: Make edit view and write update function.

// web.php

Route::get('/edit/ticket/{id}','TicketController@edit');
Route::post('/edit/ticket/{id}','TicketController@update');

Switch to the controller and write the edit function.

/**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $ticket = Ticket::where('user_id', auth()->user()->id)
                        ->where('id', $id)
                        ->first();

        return view('user.edit', compact('ticket', 'id'));
    }

Write edit.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div><br />
@endif
    <div class="row">
    <form method="post" action="{{action('TicketController@update', $id)}}" >
        {{csrf_field()}}
        <input name="_method" type="hidden" value="PATCH">
        <div class="form-group">
            <input type="hidden" value="{{csrf_token()}}" name="_token" />
            <label for="title">Ticket Title:</label>
            <input type="text" class="form-control" name="title" value={{$ticket->title}} />
        </div>
        <div class="form-group">
            <label for="description">Ticket Description:</label>
            <textarea cols="5" rows="5" class="form-control" name="description">{{$ticket->description}}</textarea>
        </div>
        <button type="submit" class="btn btn-primary">Update</button>
        </form>
    </div>
</div>
@endsection

Also, write the update function.

     /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $ticket = new Ticket();
        $data = $this->validate($request, [
            'description'=>'required',
            'title'=> 'required'
        ]);
        $data['id'] = $id;
        $ticket->updateTicket($data);

        return redirect('/home')->with('success', 'New support ticket has been updated!!');
    }

Also, code the model function updateTicket().

public function updateTicket($data)
{
        $ticket = $this->find($data['id']);
        $ticket->user_id = auth()->user()->id;
        $ticket->title = $data['title'];
        $ticket->description = $data['description'];
        $ticket->save();
        return 1;
}

Step 7: Code the delete ticket function.

Define the route for the function.

Route::delete('/delete/ticket/{id}','TicketController@destroy');

Now, full index.blade.php view is like the following.

@extends('layouts.app')

@section('content')
<div class="container">
    <table class="table table-striped">
        <thead>
            <tr>
              <td>ID</td>
              <td>Title</td>
              <td>Description</td>
              <td colspan="2">Action</td>
            </tr>
        </thead>
        <tbody>
            @foreach($tickets as $ticket)
            <tr>
                <td>{{$ticket->id}}</td>
                <td>{{$ticket->title}}</td>
                <td>{{$ticket->description}}</td>
                <td><a href="{{action('TicketController@edit',$ticket->id)}}" class="btn btn-primary">Edit</a></td>
                <td>
                    <form action="{{action('TicketController@destroy', $ticket->id)}}" method="post">
                    {{csrf_field()}}
                    <input name="_method" type="hidden" value="DELETE">
                    <button class="btn btn-danger" type="submit">Delete</button>
                    </form>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
<div>
@endsection

The whole TicketController.php file looks like the following.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Ticket;

class TicketController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tickets = Ticket::where('user_id', auth()->user()->id)->get();
        
        return view('user.index',compact('tickets'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('user.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $ticket = new Ticket();
        $data = $this->validate($request, [
            'description'=>'required',
            'title'=> 'required'
        ]);
       
        $ticket->saveTicket($data);
        return redirect('/home')->with('success', 'New support ticket has been created! Wait sometime to get resolved');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $ticket = Ticket::where('user_id', auth()->user()->id)
                        ->where('id', $id)
                        ->first();

        return view('user.edit', compact('ticket', 'id'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $ticket = new Ticket();
        $data = $this->validate($request, [
            'description'=>'required',
            'title'=> 'required'
        ]);
        $data['id'] = $id;
        $ticket->updateTicket($data);

        return redirect('/home')->with('success', 'New support ticket has been updated!!');
    }

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

        return redirect('/home')->with('success', 'Ticket has been deleted!!');
    }
}

Finally, our Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch is over.

 

The post Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/10/15/laravel-5-5-crud-example-tutorial/feed/ 41
Laravel Dependency Injection Tutorial Example https://appdividend.com/2017/10/14/laravel-dependency-injection-tutorial-example/ https://appdividend.com/2017/10/14/laravel-dependency-injection-tutorial-example/#respond Sat, 14 Oct 2017 17:11:32 +0000 http://localhost/appdividend/?p=1151 Laravel Dependency Injection Tutorial Example

Laravel Dependency Injection Tutorial Example is today’s leading topic. We are using Laravel 5.5 so, it is Laravel 5.5 Dependency Injection Tutorial. Dependency injection is the phrase that necessarily means the class dependencies that are “injected” into a class via a constructor or, in some cases, “setter” methods. We can inject the classes into the another class’s constructor […]

The post Laravel Dependency Injection Tutorial Example appeared first on AppDividend.

]]>
Laravel Dependency Injection Tutorial Example

Laravel Dependency Injection Tutorial Example is today’s leading topic. We are using Laravel 5.5 so, it is Laravel 5.5 Dependency Injection TutorialDependency injection is the phrase that necessarily means the class dependencies that are “injected” into a class via a constructor or, in some cases, “setter” methods. We can inject the classes into the another class’s constructor and then get the object of that class, and through that object, we can access its methods and properties.

Laravel Dependency Injection Tutorial Example

We will be going to understand with an example.

Step 1: Install Laravel 5.5 Project.

Type the following command.

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

Now, configure the database.

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

Now, we need to seed the Users table

Type the following command.

php artisan make:seeder UsersTableSeeder

Step 2: Write the queries and seed the table.

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
          DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
           DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
            DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
             DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Type the following command in your terminal.

php artisan db:seed

It will create the rows for our table.

Step 2: Dependency Injection Code.

Make one controller called UserController by typing the following command.

php artisan make:controller UserController --resource

Also, we need to make one web route for our application.

So, in the web.php file, write the following line of code.

Route::get('/users', 'UserController@index');

We need to include our User.php model into the UserController.php file.

use App\User;

We also need to write the constructor for the class to inject the dependencies.

/**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  User  $users
     * @return void
     */
    public function __construct(User $users)
    {
        $this->users = $users;
    }

In index() function, write the following lines of code.

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $id = 2;
        $user = $this->users->find($id);
        return $user;
    }

In a real-life example, we need to pass the $id as a parameter of that function, but this is a demo, so not needed here.

Now, start the laravel server by the typing following command.

php artisan serve

Hit the following URL.

http://localhost:8000/users

You will see an output like this.

{
 "id": 2,
 "name": "qvzbXlneUl",
 "email": "W4PvNyLAdX@gmail.com",
 "created_at": null,
 "updated_at": null
}

So, we have successfully injected the class into the constructor and make one object of that model, and through that object, we can now access to its method and displayed the data from the database.

In Laravel, you can also direct Inject the class into its method and that time; you do not need even to build the object, Laravel will make for you through Resolution API.
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
 public function index(User $users)
 {
   $id = 2;
   $user = $users->find($id);
   return $user;
 }

Our, Laravel Dependency Injection Tutorial is finally over.

For more information, please follow this Link: https://laravel.com/docs/5.5/container

The post Laravel Dependency Injection Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2017/10/14/laravel-dependency-injection-tutorial-example/feed/ 0