Laravel Interview question

Laravel Interview Question

Pinterest LinkedIn Tumblr

1) What is Laravel?

Laravel is a free open source “PHP framework” based on MVC design pattern. Laravel has inbuilt features like Eloquent ORM, Blade Template engine, Built-in command-line tool “Artisan”, database structure and build their migration.

2) What are the pros and cons of using the Laravel Framework?

  1. Built-in command-line tool “Artisan” for creating a code skeleton, database structure and build their migration.
  2. Laravel Framework has in-built lightweight blade template engine to speed up compiling task can create layout easily.
  3. Hassle code reusability.
  4. Eloquent ORM With PHP Active Record Implementation.

3) Explain Events in laravel?

Event:  An event class is a data container which holds the information related to the event. Source: https://laravel.com/docs/5.7/events

First, we need to add line within a folder app/provider/EventServiceProvider.php

protected $listen = [
    'App\Events\TaskEvent' => [
        'App\Listeners\SendTaskEventNotification',
    ],
];
php artisan event: generate

After the run, this command event is successful will create within the folder app/event/TaskEvent

4) Explain validations in laravel?

 Laravel is providing validation to provide security to handle form before goes to the database. By default, laravel base controller class uses Validation Requests traits which provides a convenient method to validate all incoming HTTP requests coming from the client. We can also validate data in laravel by creating From Request.

Example:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
   // The blog post is valid...
}

Above Example we checking in-store function apply the rule for validation using validate() function example: Title is required, unique, Maximum length is 255.

5) List some features of laravel 5.0?

  1. Inbuilt CRSF (cross-site request forgery ) Protection.
  2. Inbuilt paginations :  
  3. Reverse Routing : 
  4. Example: Route::get(‘login’, ‘users@login’);
  5. View: {{ HTML::link_to_action(‘users@login’) }}
  6. Query builder : The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
  7. Route caching :
  8. Database Migration :
  9. IOC (Inverse of Control) Container Or service container.

6) What is PHP artisan. List out some artisan commands?

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 is the list of some artisan command Example:

php artisan serve
php artisan list
php artisan help
php artisan make
php artisan --version
php artisan make model model_name
php artisan make controller controller_name

List some default packages provided by Laravel 5.6?

7) Below are list of some official/ default packages provided by Laravel 5.6

  1. Cashier: We can integrate Stripe and Braintree payment gateway via Cashier.
  2. Envoy: Laravel Envoy we can easily setup tasks for deployment, using artisan command.
  3. Passport: Passport is like authentication to maintain the user session while using API.
  4. Scout: Sout using for full-text search. 
  5. Socialite: In laravel have authentication, laravel also provides a simple, way to authenticate OAuth providers using Laravel Socialite. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, GitLab and Bitbucket.
  6. Horizon: Horizon provides a dashboard and code driven configuration in laravel this is powered by Redis Queues, Horizon allows you to easily monitor key metrics of our queue system such as job throughput, runtime, and job failures.

8) What is named routes in Laravel?

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');

9) What is database migration? How to create migration via artisan?

Migration is like version control for the database. that allows to modify and share with the team database schema.
Use below commands to create migration data via artisan.
// creating Migration

php artisan make:migration create_users_table

10) What are service providers?

Service Providers are a 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.

11) Explain the Laravel service container?

One of the most powerful features 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.

Example:

<?php
namespace App\Http\Controllers;
use App\User;
use App\Repositories\UserRepository;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
    protected $users;
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
    public function show($id)
    {
        $user = $this->users->find($id);
        return view('user.profile', ['user' => $user]);
    }
}
?>

12) What is a composer?

A 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.

13) What is dependency injection in Laravel?

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 on a dependent object (a client) that would use it. The service is made part of the client’s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

Href: https://en.wikipedia.org/wiki/Dependency_injection

You can do dependency injection via Constructor, setter and property injection.

14) What is Laravel Contract’s ?

Laravel’s Contracts are a set of interfaces that define the core services provided by the framework.

For example, an Illuminate\Contracts\Queue\Queue contract defines the methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed for sending an e-mail.

15) What is Laravel eloquent?

Laravel’s Eloquent ORM is straightforward Active Record execution for working with your database. Laravel furnishes a wide range of approaches to cooperate with your database, Eloquent is most remarkable of them. Every database table has a relating “Model” which is utilized to cooperate with that table. Models enable you to question for information in your tables, just as addition 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 the tag is ‘new’

$products= Product::where('tag','new');
// Inserting a new record 
 $product = new Product;
 $product->title = "Iphone 7";
 $product->price = "$700";
 $product->tag= 'iphone';
 $product->save();

16) How to enable query log in Laravel?   

Use the enableQueryLog method to enable query log in Laravel

     DB::connection()->enableQueryLog(); 


   You can get an array of the executed queries by using getQueryLog method:

     $queries = DB::getQueryLog();

17)  How to turn off CSRF protection for a specific route in Laravel?

To turn off CRSF protection in Laravel 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);
}

18) What are the traits in Laravel?

PHP Traits are basically a gathering of strategies that you need to incorporate inside another class. A Trait, similar to a dynamic class, can’t be started up independent from anyone else. The quality is made to decrease the constraints of single legacy in PHP by empowering a designer to reuse sets of techniques unreservedly in a few free classes living in various class pecking orders.

Here is an example of a 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'

19) Does Laravel support caching?

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.

20) Explain Laravel’s Middleware?

As the name recommends, Middleware goes about as a broker among solicitation and reaction. It is a kind of separating component. For instance, Laravel incorporates a middleware that confirms whether the client of the application is validated or not. In the event that the client is verified, he will be diverted to the landing page else, he will be diverted 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.

21) What is Lumen?

Lumen is PHP micro-framework that built on Laravel’s top components. It is created by Taylor Otwell. It is a 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

22) Explain Bundles in Laravel?

In Laravel, groups are additionally called bundles. Bundles are the essential method to expand the usefulness of Laravel. Bundles may be anything from an incredible method to work with dates like Carbon, or a whole BDD testing structure like Behat.In Laravel, you can make your custom bundles as well.

23) How to use the custom table in Laravel Modal?

we can use the custom table in Laravel by overriding protected $table property of Eloquent.

Below is sample uses

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

24) List types of relationships available in Laravel Eloquent?

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

25) Why are migrations necessary?

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.

26) Provide System requirements for installation of Laravel framework?

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

27) List some Aggregates methods provided by query builder in Laravel ?

count()

max()

min()

avg()

sum()

28) What is passport?

Laravel as of now makes it simple to perform verification by means of customary login structures, however shouldn’t something be said about APIs? APIs regularly use tokens to confirm clients and don’t keep up session state between solicitations. Laravel makes API validation a breeze utilizing Laravel Passport, which gives a full OAuth2 server execution for your Laravel application in merely minutes. Visa is based over the League OAuth2 server that is kept up by Andy Millington and Simon Hamp.

29) What is Sout?

Laravel Scout gives a straightforward, driver-based answer for adding full-content hunt to your Eloquent models. Utilizing model spectators, Scout will consequently keep your hunt files in a state of harmony with your Eloquent records.

Currently, Scout ships with an Algolia driver; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations

30) What is Socialite?

Not with standing a run of the mill, structure-based confirmation, Laravel likewise gives a basic, helpful approach to verify with OAuth suppliers utilizing Laravel Socialite. A socialite at present supports confirmation with Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket.

31) Guzzle http client GET and POST request example in Laravel 5?

we require to utilize programming interface of other sites like Facebook, Instagram, WordPress and so on, and we need to utilize their programming interface then we need to two alternatives twist and another is Http chug. So I think laravel give Guzzle Http customer author bundle and it’s astonishing. we essentially utilize that bundle and get an API reaction in JSON or HTML as we need.

Along these lines, we need to simply utilize guzzlehttp/chug writer bundle and we can just utilize their strategies that way we don’t require to run twist solicitation or anything. So we should perceive how it takes a shot at getting demand with Guzzle HTTP customer, post demand with Guzzle HTTP customer, head demand with Guzzle HTTP customer, put a solicitation with Guzzle HTTP customer, erase demand with Guzzle HTTP customer, fix demand with Guzzle HTTP customer, mixtures demand with Guzzle HTTP customer.

How to install guzzle 

composer require guzzlehttp/guzzle:~6.0




Write A Comment