Sunday, June 7, 2020

Product Category Demo in laravel

https://drive.google.com/file/d/1kuyeT3LA22IuN3o_kypOyXesEXMLv31e/view?usp=sharing

Form Submit using Ajax + Laravel with File Upload

HTML
-----------------------------------------

<!--begin::Entry-->
<div class="main-content p-t-b-50 pt-155">
    <!--begin::Container-->
    <div class="container">
        <!--begin::Card-->
        <div class="card card-custom gutter-b">
            <div class="card-header">
                <h3 class="card-title">Capsule Create</h3>
            </div>
            <!--begin::Form-->
            <form onsubmit="return false;" id="capsule_frm">
                @csrf
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <input type="hidden" class="form-control" name='id' id="moduleId" value="{{$data->id ?? ''}}">
                            <div class="form-group">
                                <label for="nominee">Nominee</label>
                                <input type="text" class="form-control" name='nominee' id="nominee" placeholder="Enter Nominee Emain Address" value="{{$data->nominee ?? ''}}" >
                                <div class="error text-danger" id='nominee_error'></div>
                            </div>
                            <div class="form-group">
                                <label for="release_on">Release On</label>
                                <select class="form-control" name='release_on' id="release_on">
                                    <option value="die" {{(!empty($data->release_on) && $data->release_on == 'die') ? 'selectd' : ''}}>When I die</option>
                                    <option value="future_date" {{(!empty($data->release_on) && $data->release_on == 'future_date') ? 'selected="selected"' : ''}}>Future Date</option>
                                </select>
                                <div class="error text-danger" id='release_on_error'></div>
                            </div>
                            <div class="form-group" id="release_date-box">
                                <label for="release_date">Release Date</label>
                                <input type="date" disabled class="form-control datepicker" data-formet="dd-mm-yy"  name='release_date' id="release_date" placeholder="Enter Release Date" value="{{!empty($data->release_date) ? date('Y-m-d', strtotime($data->release_date)) : ''}}" >
                                <div class="error text-danger" id='release_date_error'></div>
                            </div>
                            <div class="form-group">
                                <label for="expire_date">Expire Date</label>
                                <input type="date" class="form-control datepicker" data-formet="dd-mm-yy"  name='expire_date' id="expire_date" placeholder="Enter Release Date" value="{{!empty($data->expire_on) ? date('Y-m-d', strtotime($data->expire_on)) : ''}}" >
                                <div class="error text-danger" id='expire_date_error'></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="capsule_type">Capsule Type</label>
                                @if(!empty($data->id) && !empty($data->capsule_type_id))
                                    <!-- <input type="hidden" name="capsule_type" value="{{$data->capsule_type_id}}"> -->
                                @endif
                                <select class="form-control" name='capsule_type' id="capsule_type" {{!empty($data->id) ? "disabled=disabled" : ""}} >
                                    @foreach($capsuleType as $ct)
                                    <option value="{{$ct->id}}" data-slug="{{ $ct->slug ?? ''}}" {{(!empty($data->capsule_type_id) && $ct->id == $data->capsule_type_id) ? 'selected' : ''}}>{{$ct->name}}</option>
                                    @endforeach
                                </select>
                                <div class="error text-danger" id='capsule_type_error'></div>
                            </div>
                            <div class="form-group" id="video-box">
                                @if(!isset($data))
                                <label for="video">Upload Video Capsule</label>
                                <input type="file" disabled name="video" id="video">
                                <input type="hidden" name="old_video" id="old_video" value="{{$data->video ?? ''}}">
                                @endif
                                <a href="{{$data->video ?? ''}}">{{$data->video ?? ''}}</a>
                                <div class="error text-danger" id='video_error'></div>
                            </div>
                            <div class="form-group" id="audio-box">
                                @if(!isset($data))
                                <label for="audio">Upload Audio Capsule</label>
                                <input type="file" disabled name="audio" id="audio">
                                <input type="hidden" name="old_audio" id="old_audio"  value="{{$data->audio ?? ''}}">
                                @endif
                                <a href="{{$data->audio ?? ''}}">{{$data->audio ?? ''}}</a>
                                <div class="error text-danger" id='audio_error'></div>
                            </div>
                            <div class="form-group">
                                <label for="text">Text</label>
                                <textarea class="form-control"  name='text' id="text" placeholder="Enter text">{{ $data->text ?? ""}}</textarea>
                                <div class="error text-danger" id='text_error'></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <input type="button" id="submit_info" class="btn btn-primary" value="Save"/>
                    <a type="button" id="back_btn" class="btn btn-default" href="{{route('client.capsule')}}" value="Back">Back</a>
                    <span class="submit_notification">
                        @if (Session::has('message'))
                        <div class="text-{{ Session::get('status') }}">{{ Session::get('message') }}</div>
                        @endif
                    </span>
                </div>
            </form>
            <!--end::Form-->
        </div>
    </div>
</div>

Javascript
----------------------------------------------------------


<script type="text/javascript">
    var getUser   = "{{ route('user_drop') }}";
    var getCapsuleType   = "{{ route('capsule_type_drop') }}";
    var saveUrl   = "{{ (!isset($data)?url('capsule/save'):url('capsule/update')) }}";
    var returnUrl = "{{ url('capsule') }}";
    var capsuleType = "{{!empty($data->capsule_type_id) ? $data->capsule_type_id : 1}}";
    var releaseOn = "{{!empty($data->release_on) ? $data->release_on : 'die'}}";
   
function checkCapsuleType(type){
    if(type == 2) {
        $('#video-box').show();
        $('#audio-box').hide();
        $('#video-box').find('#video').removeAttr('disabled');
        $('#audio-box').find('#audio').attr('disabled', 'disabled');
    } else if(type == 3) {
        $('#audio-box').show();
        $('#video-box').hide();
        $('#audio-box').find('#audio').removeAttr('disabled');
        $('#video-box').find('#video').attr('disabled', 'disabled');
    } else {
        $('#video-box,#audio-box').hide();
        $('#audio').find('#audio').attr('disabled','disabled');
        $('#video').find('#video').attr('disabled', 'disabled');
    }
}

function checkReleaseOn(releaseOn){
    if(releaseOn == 'future_date') {
        $('#release_date-box').show();
        $('#release_date').removeAttr('disabled');
    } else {
        $('#release_date-box').hide();
        $('#release_date').attr('disabled', 'disabled');
    }
}

$(document).ready(function() {

    $('#video-box,#audio-box').hide();

    checkCapsuleType(capsuleType);
    checkReleaseOn(capsuleType);

    $('#capsule_type').change(function(){
        // var type = $('#capsule_type').find(":selected").data('slug');
        var type = $(this).val();
        checkCapsuleType(type);
    });

    $('#release_date-box').hide();
    checkReleaseOn(releaseOn);

    $('#release_on').change(function(){
        var releaseOn = $('#release_on').val();
        checkReleaseOn(releaseOn);
    });

    $(document).off('click', '#submit_info').on('click', '#submit_info', function() {
        var btn = $("#submit_info");
        var moduleId = $("#moduleId").val();
        var old_val = btn.val();
        var form = btn.closest('form');
        var formData = new FormData(form[0]);
        $.ajax({
            url: saveUrl,
            type: 'post',
            dataType: 'json',
            // data: form.serialize(),
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {
                $('.error,.submit_notification').html('');
                form.find(".form-control").removeClass("red-border");
                $('.btn').attr("disabled", "disabled").val("Sending...");
            },
            success: function(result) {
                $('.btn').removeAttr("disabled").val(old_val);
                form.find(':input:enabled:visible:first').focus();
                if (result.status == 'validation') {
                    $.each(result, function(i, val) {
                        if (val != "") {
                            form.find("#" + i + "_error").text(val);
                        }
                    });
                    $("body").animate({
                        scrollTop: 0
                    }, "slow");
                } else if (result.status === 'success') {
                    if (moduleId) {
                        window.location.href = returnUrl;
                    } else {
                        form[0].reset();
                        $('.submit_notification').html('<span class="text-success error">' + result.message + '</span>');
                        $('#user').val('').trigger('change');
                    }
                } else {
                    $('.error').html('');
                    $('.submit_notification').html('<span class="text-danger error">' + result.message + '</span>');
                }
            },
            error: function(e) {
                $('.btn').removeAttr("disabled").val(old_val);
                $('.submit_notification').html('<span class="text-danger error">Something Went Wrong!... Please try again after refresh</span>');
            }
        });
    });
});
</script>

PHP
-------------------------------------
public function store(Request $request)
    {
        $input = $request->all();

        $validator = Validator::make($input, [
            'capsule_type' => 'required_if:id,!=,""',
            'nominee'      => 'required',
            'text'         => 'required',
            'video'        => 'required_if:capsule_type,==,2|mimetypes:video/avi,video/mp4,video/3gpp,video/mpeg,video/quicktime|file|max:4000',
            'audio'        => 'required_if:capsule_type,==,3|mimetypes:audio/mp3,audio/mpeg|file|max:4000',
        ]);

        if ($validator->fails()) {
            $result['status']       = 'validation';
            $result['capsule_type'] = $validator->errors()->first('capsule_type');
            $result['nominee']      = $validator->errors()->first('nominee');
            $result['text']         = $validator->errors()->first('text');
            $result['video']        = $validator->errors()->first('video');
            $result['audio']        = $validator->errors()->first('audio');
        } else {
            if (isset($input['id']) && !empty($input['id'])) {
                $capsule = Capsule::find($input['id']);
                $msg     = "Updated";
            } else {
                $capsule                  = new Capsule;
                $msg                      = "Created";
                $capsule->capsule_type_id = isset($input['capsule_type']) ? $input['capsule_type'] : "";
            }

            $video = $request->file('video');
            $audio = $request->file('audio');
            $user_id =auth('client')->user()->id;

            //Move Uploaded audio
            if (!empty($audio)) {
                $audioName       = str_slug($audio->getClientOriginalName(), "-") . '_' . $user_id . '_' . time() . "." . $audio->getClientOriginalExtension();
                $destinationPath = public_path('upload/audio');
                $audio->move($destinationPath, $audioName);
                $capsule->audio = $audioName;
            }
            // else {
            //     $audioName = $input['old_audio'];
            // }

            //Move Uploaded video
            if (!empty($video)) {
                $videoName       = str_slug($video->getClientOriginalName(), "-") . '_' . $user_id . '_' . time() . "." . $video->getClientOriginalExtension();
                $destinationPath = public_path('upload/video');
                $video->move($destinationPath, $videoName);
                $capsule->video = $videoName;
            }
            // else {
            //     $videoName = $input['old_video'];
            // }

// $theOtherKey = env('APP_KEY');

// $text = $input['text'];

// $encriptText = Crypt::encryptString($text);
// $encriptText = Crypt::encryptString($encriptText);

// $decriptText = Crypt::decryptString($encriptText);
// $decriptText = Crypt::decryptString($decriptText);

// print_r($encriptText);
// echo "<br>";
// print_r($decriptText);
// exit;

            $capsule->user_id      = $user_id;
            $capsule->nominee      = isset($input['nominee']) ? $input['nominee'] : "";
            $capsule->text         = isset($input['text']) ? $input['text'] : "";
            $capsule->release_on   = isset($input['release_on']) ? $input['release_on'] : "die";
            $capsule->release_date = !empty($input['release_date']) ? date('Y-m-d', strtotime($input['release_date'])) : null;
            $capsule->expire_on    = !empty($input['expire_date']) ? date('Y-m-d', strtotime($input['expire_date'])) : null;
            $capsule->revision     = ($capsule->revision + 1);
            $capsule->admin_key    = rand();
            $capsule->client_key   = rand();

            if ($capsule->save()) {
                $result['status']  = 'success';
                $result['message'] = 'Capsule ' . $msg . ' successfully';
            } else {
                $result['status']  = 'error';
                $result['message'] = 'error';
            }
        }
        echo json_encode($result);

    }

Sunday, May 24, 2020

Laravel interview questions

Laravel interview questions

Laravel interview questions

What is Laravel?

Laravel is a Symfony based free open-source PHP web framework. It is created by Taylor Otwell and allows developers to write expressive, elegant syntax. Laravel comes with built-in support for user authentication and authorization which is missing in some most popular PHP frameworks like CodeIgniter, CakePHP.Here you will find Latest Laravel interview questions and answer that helps you crack Laravel Interviews.

Quick Questions About Laravel

is written In PHP Programming (PHP 7)
Laravel is a PHP Framework for Developing websites and mobile API's.
Laravel is developed By Taylor Otwell
Laravel is Based on MVC architectural pattern
Laravel Dependencies Composer, OpenSSL, PDO, Mbstring, etc.
Laravel Licence MIT License
Laravel Current Stable release 6.9.0
Download Laravel interview questions PDF
Below are the list of Best Laravel interview questions and Answers
Laravel is a free open source "PHP framework" based on the MVC design pattern.
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.
An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel events provides a simple observer implementation, that allowing you to subscribe and listen for various events/actions that occur in your application.
All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.
In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database.
Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.
Laravel validation Example
$validatedData = $request->validate([
            'name' => 'required|max:255',
            'username' => 'required|alpha_num',
            'age' => 'required|numeric',
        ]);

You can install Laravel via composer by running below command.
composer create-project laravel/laravel your-project-name version
Also Read Core PHP Interview Questions and Answers for 2019
Laravel 6 features
  • Inbuilt CRSF ( cross-site request forgery ) Protection.
  • Inbuilt paginations
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • IOC (Inverse of Control) Container Or service container.
  • Job middleware
  • Lazy collections
PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisan command:-
  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan –versian
  • php artisan make model model_name
  • php artisan make controller controller_name
Below are a list of some official/ default packages provided by Laravel
  • Cashier
  • Envoy
  • Passport
  • Scout
  • Socialite
  • Horizon
  • Telescope
Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Urls more comfortably.
You can specify named routes by chaining the name method onto the route definition:
Route::get('user/profile', function () {
    //
})->name('profile');

You can specify route names for controller actions:
Route::get('user/profile', 'UserController@showProfile')->name('profile');
Once you have assigned a name to your routes, you may use the route's name when generating URLs or redirects via the global route function:
// Generating URLs...
$url = route('profile');
// Generating Redirects...
return redirect()->route('profile');
Migrations are like version control for your database, that’s allow your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.
Use below commands to create migration data via artisan.
// creating Migration
php artisan make:migration create_users_table
Service Providers are central place where all laravel application is bootstrapped . Your application as well all Laravel core services are also bootstrapped by service providers.
All service providers extend the Illuminate\Support\ServiceProvider class. Most service providers contain a register and a boot method. Within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.
You can read more about service provider from here
One of the most powerful feature of Laravel is its Service Container . It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel.
Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.
Composer is a tool for managing dependency in PHP. It allows you to declare the libraries on which your project depends on and will manage (install/update) them for you.
Laravel utilizes Composer to manage its dependencies.
In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client’s state.[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.
https://en.wikipedia.org/wiki/Dependency_injection
You can do dependency injection via Constructor, setter and property injection.
Laravel's Contracts are nothing but a set of interfaces that define the core services provided by the Laravel framework.
Read more about laravel Contract’s
Laravel Facades provides a static like an interface to classes that are available in the application’s service container. Laravel self-ships with many facades which provide access to almost all features of Laravel ’s. Laravel facades serve as “static proxies” to underlying classes in the service container and provide benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace. You can easily access a facade like so:

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});
Laravel's Eloquent ORM is simple Active Record implementation for working with your database. Laravel provide many different ways to interact with your database, Eloquent is most notable of them. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
Below is sample usage for querying and inserting new records in Database with Eloquent.

// Querying or finding records from products table where tag is 'new'
$products= Product::where('tag','new');
// Inserting new record 
 $product =new Product;
 $product->title="Iphone 7";
 $product->price="$700";
 $product->tag='iphone';
 $product->save();
Use the enableQueryLog method to enable query log in Laravel

DB::connection()->enableQueryLog(); 
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();
Laravel reverse routing is generating URL's based on route declarations. Reverse routing makes your application so much more flexible. It defines a relationship between links and Laravel routes. When a link is created by using names of existing routes, appropriate Uri's are created automatically by Laravel. Here is an example of reverse routing.
// route declaration
Route::get('login', 'users@login');
Using reverse routing we can create a link to it and pass in any parameters that we have defined. Optional parameters, if not supplied, are removed from the generated link.
{{ HTML::link_to_action('users@login') }}
It will automatically generate an Url like http://xyz.com/login in view.
To turn off CRSF protection in Larave l add following codes in “app/Http/Middleware/VerifyCsrfToken.php”
 
//add an array of Routes to skip CSRF check
private $exceptUrls = ['controller/route1', 'controller/route2'];
 //modify this function
public function handle($request, Closure $next) {
 //add this condition foreach($this->exceptUrls as $route) {
 if ($request->is($route)) {
  return $next($request);
 }
}
return parent::handle($request, $next);
} 
PHP Traits are simply a group of methods that you want include within another class. A Trait, like an abstract class cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
Here is an example of trait.
trait Sharable {
 
  public function share($item)
  {
    return 'share this item';
  }
 
}
You could then include this Trait within other classes like this:

class Post {
 
  use Sharable;
 
}
 
class Comment {
 
  use Sharable;
 
}
Now if you were to create new objects out of these classes you would find that they both have the share() method available:

$post = new Post;
echo $post->share(''); // 'share this item' 
 
$comment = new Comment;
echo $comment->share(''); // 'share this item'
Yes, Laravel supports popular caching backends like Memcached and Redis .
By default, Laravel is configured to use the file cache driver , which stores the serialized, cached objects in the file system.For large projects, it is recommended to use Memcached or Redis.
As the name suggests, Middleware acts as a middleman between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.
There are two types of Middleware in Laravel.
Global Middleware: will run on every HTTP request of the application.
Route Middleware : will be assigned to a specific route.
Read more about Laravel middlewares
Lumen is PHP micro-framework that built on Laravel’s top components.It is created by Taylor Otwell. It is perfect option for building Laravel based micro-services and fast REST API’s. It’s one of the fastest micro-frameworks available.
You can install Lumen using composer by running below command
composer create-project --prefer-dist laravel/lumen blog
In Laravel, bundles are also called packages. Packages are the primary way to extend the functionality of Laravel. Packages might be anything from a great way to work with dates like Carbon, or an entire BDD testing framework like Behat.In Laravel, you can create your custom packages too. You can read more about packages from here
You can use custom table in Laravel by overriding protected $table property of Eloquent.

Below is sample uses

class User extends Eloquent{
 protected $table="my_user_table";

} 
Below are types of relationships supported by Laravel Eloquent ORM.
  • One To One
  • One To Many
  • One To Many (Inverse)
  • Many To Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations
You can read more about relationships in Laravel Eloquent from here
Migrations are necessary because:
  • Without migrations, database consistency when sharing an app is almost impossible, especially as more and more people collaborate on the web app.
  • Your production database needs to be synced as well.
In order to install Laravel, make sure your server meets the following requirements:
  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
In Laravel, we can use $request->ajax() method to check request is ajax or not.
Example:
      public function saveData(Request $request)
        {
            if($request->ajax()){
                return "Request is of Ajax Type";
            }
            return "Request is of Http type";
        }
Inversion of control is a design pattern that is used for decoupling components and layers of a system. Inversion of control(IOC) is implemented through injecting dependencies into a component when it is constructed.
Singleton design pattern is a creational pattern that is used whenever only one instance an object is needed to be created. In this pattern, you can't initialize the class.
Dependency injection is way to pass one obeject dependencies to another object.It is a broader form of inversion of control (IOC).
There are basically 3 types of dependency injection:
  • constructor injection
  • setter injection
  • Interface injection
It is a serverless deployment platform that is powered by AWS. Laravel Vapor provides on-demand auto-scaling with zero server maintenance.
Pros of using Laravel Framework
  1. Laravel framework has in-built lightweight blade template engine to speed up compiling task and create layouts with dynamic content easily.
  2. Hassles code reusability.
  3. Eloquent ORM with PHP active record implementation
  4. Built in command line tool “Artisan” for creating a code skeleton , database structure and build their migration
Cons of using laravel Framework
  1. Development process requires you to work with standards and should have real understanding of programming
  2. Laravel is new framework and composer is not so strong in compare to npm (for node.js) , ruby gems and python pip .
  3. Development in laravel is not so fast in compare to ruby on rails.
  4. Laravel is lightweight so it has less inbuilt support in compare to django and rails. But this problem can be solved by integrating third party tools, but for large and very custom websites it may be a tedious task
The cursor method in the Laravel is used to iterate the database records using a cursor. It will only execute a single query through the records. This method is used to reduce the memory usage when processing through a large amount of data.
Example of Laravel Cursor
foreach (Product::where(‘name’, ‘Bob’)->cursor() as $fname) {
//do some stuff
}

In Laravel, dd() is a helper function used to dump a variable's contents to the browser and stop the further script execution. It stands for Dump and Die . It is used to dump the variable/object and then die the script execution. You can also isolate this function in a reusable functions file or a Class.
In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page. So, when the Laravel performs blade file, it first verifies if you have extended a master layout, if you have extended one, then it moves to the master layout and commences getting the @sections.
You can use php artisan cache:clear commnad to clear Cache in Laravel.

Product Category Demo in laravel

https://drive.google.com/file/d/1kuyeT3LA22IuN3o_kypOyXesEXMLv31e/view?usp=sharing