Laravel Interview Questions

Q:-1 What is Laravel?

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern.

Q:-1(a) What is Server Requirements for Laravel 5.6?
  • 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

Laravel Interview Questions | Installation

Q:-2 How to Install Laravel via Composer?
  • code
  • source
  1. composer create-project –prefer-dist laravel/laravel myproject
Q:-2(a) How to Install any Specific version of Laravel via Composer?
  • code
  • source
  1. //Composer Command To Install Laravel:
  2. composer create-project –prefer-dist laravel/laravel ProjectName “VersionNo.*”
  3. //Example: Install Laravel 5.4 using Composer
  4. composer create-project –prefer-dist laravel/laravel blog “5.4.*
Q:-3 What is Lumen?
  1. Lumen is a micro-framework provided by Laravel.
  2. It is developed by creator of Laravel Taylor Otwell.
  3. It is mostly used for creating RESTful API’s & microservices.
  4. Lumen is built on top components of Laravel.
Q:-3(a) How to Install Lumen via Composer?

Composer is PHP dependency manager used for installing dependencies of PHP applications.

  • code
  • source
  1. composer create-project –prefer-dist laravel/lumen myproject
Q:-4 What is php artisan?
    1. Artisan is the command-line interface included with Laravel.
    2. It provides a number of helpful commands that can assist you while you build your application.
    1. To view a list of all available Artisan commands, you may use the list command:
  • code
  • source
  1. php artisan list //it will all commands
  2. php artisan –version //to check current installed laravel version
Q:-4(a) List mostly used artisan commands?
    1. To view a list of all available Artisan commands, you may use the list command:
  • code
  • source
  1. php artisan list //it will all commands
  2. php artisan –version //to check current installed laravel version
    1. Mostly used Artisan commands are:
  • code
  • source
  1. php artisan list //it will all commands
  2. php artisan –version //to check current installed laravel version
  3. //Clear view caches
  4. php artisan view:clear
  5. //Clear cache
  6. php artisan cache:clear
  7. //Make authorization views and scaffolding
  8. php artisan make:auth
  9. //Make a new model
  10. php artisan make:model model-name
  11. //Make a new empty controller
  12. php artisan make:controller MyController
Q:-5 List benefits of using Laravel over other PHP frameworks?

Reasons why Laravel is the best PHP framework:

  1. Artisan – A Command-Line Interface
  2. Migrations & Seeding
  3. Blade Template Engine
  4. Middleware – HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
  5. Eloquent ORM + Built-in Database Query Builder
  6. Routing (RESTful routing)
  7. Inbuilt packages – Authentication, Cashier, Scheduler, SSH, Socialite
  8. Security
  9. Unit Testing – Built-in unit testing and simply readable impressive syntax
  10. Caching – Laravel provides an expressive, unified API for various caching backends

Q:-6 List most important packages provided by Laravel?

Following are some official packages provided by Laravel:

Authentication:

Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box.

  • code
  • source
  1. //Make authorization views and scaffolding
  2. php artisan make:auth
Passport:
  1. In Short, Laravel provides Passport for API Authentication.
  2. Laravel Passport is an OAuth2 server and API authentication package that is simple to use
Cashier:

Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services

Scout:
    1. Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models.
    2. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records
  1. 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.
Socialite:
  1. Laravel’s Socialite package makes it simple to authenticate your users to social login
  2. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket.

You may also like – Core PHP Interview Questions

Q:-7 How to turn off CRSF in Laravel?
Disable CSRF protection for all routes In Laravel:
  • code
  • source
  1. Remove or comment out this line in app\Http\Kernel.php
  2. \App\Http\Middleware\VerifyCsrfToken::class,
To turn off or disable CRSF protection for some specific routes in Laravel:

open “app/Http/Middleware/VerifyCsrfToken.php” file and add your routes in $except array.

  • code
  • source
  1. namespace App\Http\Middleware;
  2. use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
  3. class VerifyCsrfToken extends BaseVerifier
  4. {
  5. /**
  6. * The URIs that should be excluded from CSRF verification.
  7. *
  8. * @var array
  9. */
  10. protected $except = [
  11. ‘stripe/*’,
  12. ‘payment/verify/{id}/*’,
  13. ‘some/route/path’,
  14. ];
  15. }
Q:-8 How can you change your default database type?

By default Laravel is configured to use MySQL.

In order to change your default database edit your config/database.php

  • code
  • source
  1. search for default => env(‘DB_CONNECTION’, ‘mysql’)
  2. and change it to whatever you want (like default => env(‘DB_CONNECTION’, ‘sqlite’))
Q:-9 What is ORM?

ORM: Object-relational Mapping (ORM) is a programming technique that help in converting data between incompatible type systems into object-oriented programming languages.

Q:-9(a) Which ORM are being used by laravel?

Eloquent ORM is being used by Laravel.

  • 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.
  • All Eloquent models extend Illuminate\Database\Eloquent\Model class
Eloquent Model Examples:

The easiest way to create a model instance is using the make:model artisan command

  • code
  • source
  1. php artisan make:model User

If you would like to generate a database migration when you generate the model, use:

  • code
  • source
  1. php artisan make:model User –migration
  2. //OR
  3. php artisan make:model User -m

Now look following Example:

  • code
  • source
  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class User extends Model
  4. {
  5. //Your code
  6. }

Eloquent will assume the User model stores records in the users table

You may specify a custom table by defining a table property in your model, like below:

  • code
  • source
  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class User extends Model
  4. {
  5. /**
  6. * The table associated with the model.
  7. *
  8. * @var string
  9. */
  10. protected $table = ‘my_tables’;
  11. }
Q:-9(b) List types of relationships available in Laravel Eloquent?
  1. Eloquent relationships are defined as methods on your Eloquent model classes
  2. Relationships supported by Laravel Eloquent ORM:
    1. One To One – hasOne
    2. One To Many – hasMany
    3. One To Many(Inverse) – belongsTo
    4. Many To Many – belongsToMany
    5. Has Many Through – hasManyThrough
    6. Polymorphic Relations
    7. Many To Many Polymorphic Relations
Q:-10 Which Template Engine used by Laravel?

Blade is the simple, yet powerful templating engine provided with Laravel.

Q:-10(a) What is benefits of using “Blade” Template in Laravel?

Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views

In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application

Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

 

Q:-11 How to enable maintenance mode in Laravel?

You can enable maintenance mode in Laravel, simply by executing below command.

  • code
  • source
  1. // Enable maintenance mode
  2. php artisan down
  3. // Disable maintenance mode
  4. php artisan up
Q:-12 What is the purpose of using dd() function in laravel?

dd() – Stands for “Dump and Die”

Laravel’s dd() is a helper function ,which will dump a variable’s contents to the browser and halt further script execution.

Q:-13 What is Middleware in Laravel?

Middleware provide a convenient mechanism for filtering all HTTP requests entering in your application.

Q:-14 Explain Laravel Service Container?

The Laravel Service Container is a powerful tool for managing class dependencies and performing dependency injection.

Dependency injection is technique which means: class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

Almost all of your service container bindings will be registered within service providers

Dependency Injection Benefits:
  1. More Reusable Code
  2. More Testable Code
  3. More Readable Code
Q:-15 What are Service Providers in Laravel?
  1. Service Providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services are bootstrapped via service providers.
  2. Bootstrapping mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
Q:-15(a) How do you register a Service Provider?
  1. All service providers extend the Illuminate\Support\ServiceProvider class.
  2. Most service providers contain a register and a boot method.
  3. Within the register method, you should only bind things into the service container.
  • code
  • source
  1. php artisan make:provider MyServiceProvider
Q:-16 What are Laravel Facades?

In Short, Facades provide a “static” interface to classes that are available in the application’s service container.

All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

Facades have many benefits. They provide a short and memorable syntax that allows you to use Laravel’s features without remembering long class names that must be injected or configured manually.

Facades Vs Helper Functions: There is absolutely no practical difference between facades and helper functions. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:

  • code
  • source
  1. return View::make(‘welcome’); // facade call
  2. return view(‘welcome’); // helper call
Q:-17 Explain Events in Laravel?
  1. Laravel’s events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application
  2. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.
  3. Don’t worry if you don’t see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.
  4. A single event can have multiple listeners that do not depend on each other.
Q:-18 What is Fillable Attribute in a Laravel Model?

In eloquent ORM, $fillable is an array which contains all those fields of table which can be filled using mass-assignment.

Mass assignment, means to send an array to the model to directly create a new record in Database

  • code
  • source
  1. class User extends Model {
  2. protected $fillable = [‘name’, ’email’, ‘mobile’]; // All fields inside $fillable array can be mass-assign
  3. }
Q:-19 What is Guarded Attribute in a Laravel Model?

Guarded is the reverse of fillable.

If fillable specifies which fields to be mass assigned, guarded specifies which fields are not mass assignable.

  • code
  • source
  1. class User extends Model {
  2. protected $guarded = [‘role’]; // All fields inside the $guarded array is not mass-assignable
  3. }

If you want to block all fields from being mass-assign you can just do this.

  • code
  • source
  1. protected $guarded = [‘*’];

$fillable serves as a “white list”, $guarded functions like a black list. you should use either $fillable or $guarded.

Q:-20 What are Closures in Laravel?

A Closure is an anonymous function. Closures are often used as a callback methods and can be used as a parameter in a function.

Q:-21 What are Laravel Contracts?
  1. Laravel’s Contracts are a set of interfaces that define the core services provided by the framework.
  2. For example, a 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 e-mail
  3. Each contract has a corresponding implementation provided by the framework.
Q:-22 What are Traits in Laravel?

As of PHP 5.4, we now have a mechanism for reusing code, called Traits.

Q:-23 How to get Logged in user info in Laravel?

The laravel Auth Facade is used to get the autheticated user data as

  • code
  • source
  1. use Illuminate\Support\Facades\Auth;
  2. $user = Auth::user();
  3. print_r($user);
Q:-24 How to enable query log in Laravel?

Laravel can optionally log in memory all queries that have been run for the current request

  • code
  • source
  1. //Enable query log
  2. DB::connection()->enableQueryLog();
  3. //See query log
  4. $queries = DB::getQueryLog();
  5. //Last executed query
  6. $last_query = end($queries);
Q:-25 Does Laravel support Caching?
  1. Yes, Laravel supports popular caching mechanism like Memcached and Redis.
  2. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system.
  3. For large projects it is recommended to use Memcached or Redis.
Q:-26 What is Laravel Elixir?
Q:-27 What is Laravel Mix?
Q:-28 How can you display HTML with Blade in Laravel?
  • code
  • source
  1. {!! $text !!}

29) Why are migrations important?

Migrations are important because it allows you to share application by maintaining database consistency. Without migration, it is difficult to share any Laravel application. It also allows you to sync database.

30) Define Lumen

Lumen is a micro-framework. It is a smaller, and faster, version of a building Laravel based services, and REST API’s.

31) Explain PHP artisan

An artisan is a command-line tool of Laravel. It provides commands that help you to build Laravel application without any hassle.

32) How can you generate URLs?

Laravel has helpers to generate URLs. This is helpful when you build link in your templates and API response.

33) Which class is used to handle exceptions?

Laravel exceptions are handled by App\Exceptions\Handler class.

34) What are common HTTP error codes?

The most common HTTP error codes are:

  • Error 404 – Displays when Page is not found.
  • Error- 401 – Displays when an error is not authorized

35) Explain fluent query builder in Laravel.

It is a database query builder that provides convenient, faster interface to create and run database queries.

36) What is the use of dd() function?

This function is used to dump contents of a variable to the browser. The full form of dd is Dump and Die.

37) List out common artisan commands used in Laravel.

Laravel supports following artisan commands:

  • PHP artisan down;
  • PHP artisan up;
  • PHP artisan make:controller;
  • PHP artisan make:model;
  • PHP artisan make:migration;
  • PHP artisan make:middleware;

38) How to configure a mail-in Laravel?

Laravel provides APIs to send an email on local and live server.

39) Explain Auth.

It is a method of identifying user login credential with a password. In Laravel it can be managed with a session which takes two parameters 1) username and 2) password.

40) Differentiate between delete() and softDeletes().

  • delete(): remove all record from the database table.
  • softDeletes(): It does not remove the data from the table. It is used to flag any record as deleted.

41) How can you make real time sitemap.xml file in Laravel?

You can create all web pages of a website to tell the search engine about the organizing site content. The crawlers of search engine read this file intelligently to crawl a website.

42) Explain faker in Laravel.

It is a type of module or packages which are used to create fake data. This data can be used for testing purpose.

It is can also be used to generate: 1) Numbers, 2) Addresses, 3) DateTime, 4) Payments, and 5) Lorem text.

43) How will you check table is exists or in the database?

Use hasTable() Laravel function to check the desired table is exists in the database or not.

44) What is the significant difference between insert() and insertGetId() function in Laravel?

  • Insert(): This function is simply used to insert a record into the database. It not necessary that ID should be autoincremented.
  • InsertGetId(): This function also inserts a record into the table, but it is used when the ID field is auto-increment.

45) Explain active record concept in Laravel.

In active record, class map to your database table. It helps you to deal with CRUD operation.

46) List basic concepts in Laravel?

Following are basic concepts used in Laravel:

  • Routing
  • Eloquent ORM
  • Middleware
  • Security
  • Caching
  • Blade Templating

47) Define Implicit Controller.

Implicit Controllers help you to define a proper route to handle controller action. You can define them in route.php file with Route:: controller() method.

48) How to use the custom table in Laravel Model?

In order to use a custom table, you can override the property of the protected variable $table.

49) What is MVC framework?

It is Model, View, and Controller:

  • Model: Model defines logic to write Laravel application.
  • View: It covers UI logic of Laravel application.
  • Controller: It is work as an interface between Model, and View. It is a way how the user interacts with an application.

50) Define @include.

@include is used to load more than one template view files. It helps you to include view within another view. User can also load multiple files in one view.

51) Explain the concept of cookies.

Cookies are small file sent from a particular website and stored on PC by user’s browser while the user is browsing.

52) Which file is used to create a connection with the database?

To create a connection with the database, you can use .env file.

53) What is Eloquent?

Eloquent is an ORM used in Laravel. It provides simple active record implementation working with the database. Each database table has its Model, which used to interact with the table.

54) Name some Inbuilt Authentication Controllers of Laravel.

Laravel installation has an inbuilt set of common authentication controllers. These controllers are:

  • RegisterController
  • LoginController
  • ResetPasswordController
  • ForgetPasswordController

55) Define Laravel guard.

Laravel guard is a special component that is used to find authenticated users. The incoming requested is initially routed through this guard to validate credentials entered by users. Guards are defined in ../config/auth.php file.

56) What is Laravel API rate limit?

It is a feature of Laravel. It provides handle throttling. Rate limiting helps Laravel developers to develop a secure application and prevent DOS attacks.

57) Explain collections in Laravel.

Collections is a wrapper class to work with arrays. Laravel Eloquent queries use a set of the most common functions to return database result.

58) What is the use of DB facade?

DB facade is used to run SQL queries like create, select, update, insert, and delete.

59) What is the use of Object Relational Mapping?

Object Relational Mapping is a technique that helps developers to address, access, and manipulate objects without considering the relation between object and their data sources.

60) Explain the concept of routing in Laravel.

It allows routing all your application requests to the controller. Laravel routing acknowledges and accepts a Uniform Resource Identifier with a closure.

61) What is Ajax in Laravel?

Ajax stands for Asynchronous JavaScript and XML is a web development technique that is used to create asynchronous Web applications. In Laravel, response() and json() functions are used to create asynchronous web applications.

62) What is a session in Laravel?

Session is used to pass user information from one web page to another. Laravel provides various drivers like a cookie, array, file, Memcached, and Redis to handle session data.

63) How to access session data?

Session data be access by creating an instance of the session in HTTP request. Once you get the instance, use get() method with a “Key” as a parameter to get the session details.

64) State the difference between authentication and authorization.

Authentication means confirming user identities through credentials, while authorization refers to gathering access to the system.

65) Explain to listeners.

Listeners are used to handling events and exceptions. The most common listener in Laravel for login event is LoginListener.

66) What are policies classes?

Policies classes include authorization logic of Laravel application. These classes are used for a particular model or resource.

67) How to rollback last migration?

Use need to use artisan command to rollback the last migration.

68) What do you mean by Laravel Dusk?

Laravel Dusk is a tool which is used for testing JavaScript enabled applications. It provides powerful, browser automation, and testing API.

69) Explain Laravel echo.

It is a JavaScript library that makes possible to subscribe and listen to channels Laravel events. You can use NPM package manager to install echo.

70) What is make method?

Laravel developers can use make method to bind an interface to concreate class. This method returns an instance of the class or interface. Laravel automatically inject dependencies defined in class constructor.

71) Explain Response in Laravel.

All controllers and routes should return a response to be sent back to the web browser. Laravel provides various ways to return this response. The most basic response is returning a string from controller or route.

72) What is query scope?

It is a feature of Laravel where we can reuse similar queries. We do not require to write the same types of queries again in the Laravel project. Once the scope is defined, just call the scope method when querying the model.

73) Explain homestead in Laravel.

Laravel homestead is the official, disposable, and pre-packaged vagrant box that a powerful development environment without installing HHVM, a web server, and PHP on your computer.

74) What is namespace in Laravel?

A namespace allows a user to group the functions, classes, and constants under a specific name.

75) What is Laravel Forge?

Laravel Forge helps in organizing and designing a web application. Although the manufacturers of the Laravel framework developed this toll, it can automate the deployment of every web application that works on a PHP server.

76) State the difference between CodeIgniter and Laravel.

Parameter CodeIgniter Laravel
Support of ORM CodeIgniter does not support Object-relational mapping. Laravel supports ORM.
Provide Authentication It does provide user authentication. It has inbuilt user authentication.
Programming Paradigm It is component-oriented. It is object-oriented.
Support of other Database Management System It supports Microsoft SQL Server, ORACLE, MYSQL, IBM DB2, PostgreSQL, JDBC, and orientDB compatible. It supports PostgreSQL, MySQL, MongoDB, and Microsoft BI, but CodeIgniter additionally supports other databases like Microsoft SQL Server, DB2, Oracle, etc.
HTTPS Support Laravel supports custom HTTPS routes. The programmers can create a specific URL for HTTPS route they have defined. CodeIgniter partially support HTTPS. Therefore, programmers can use the URL to secure the data transmission process by creating PATS.

77) What is an Observer?

Model Observers is a feature of Laravel. It is used to make clusters of event listeners for a model. Method names of these classes depict the Eloquent event. Observers classes methods receive the model as an argument.

78) What is the use of the bootstrap directory?

It is used to initialize a Laravel project. This bootstrap directory contains app.php file that is responsible for bootstrapping the framework.

79) What is the default session timeout duration?

The default Laravel session timeout duration is 2 hours.

80) How to remove a complied class file?

Use clear-compiled command to remove the compiled class file.

81) In which folder robot.txt is placed?

Robot.txt file is placed in Public directory.

82) Explain API.PHP route.

Its routes correspond to an API cluster. It has API middleware which is enabled by default in Laravel. These routes do not have any state and cross-request memory or have no sessions.

83) What is named route?

Name route is a method generating routing path. The chaining of these routes can be selected by applying the name method onto the description of route.

84) what is open source software?

Open-source software is a software which source code is freely available. The source code can be shared and modified according to the user requirement.

85) Explain Loggin in Laravel.

It is a technique in which system log generated errors. Loggin is helpful to increase the reliability of the system. Laravel supports various logging modes like syslog, daily, single, and error log modes.

86) What is Localization?

It is a feature of Laravel that supports various language to be used in the application. A developer can store strings of different languages in a file, and these files are stored at resources/views folder. Developers should create a separate folder for each supported language.

87) Define hashing in Laravel.

It is the method of converting text into a key that shows the original text. Laravel uses the Hash facade to store the password securely in a hashed manner.

88) Explain the concept of encryption and decryption in Laravel.

It is a process of transforming any message using some algorithms in such way that the third user cannot read information. Encryption is quite helpful to protect your sensitive information from an intruder.

Encryption is performed using a Cryptography process. The message which is to be encrypted called as a plain message. The message obtained after the encryption is referred to as cipher message. When you convert cipher text to plain text or message, this process is called as decryption.

89) How to share data with views?

To pass data to all views in Laravel use method called share(). This method takes two arguments, key, and value.

Generally, share() method are called from boot method of Laravel application service provider. A developer can use any service provider, AppServiceProvider, or our own service provider.

90) Explain web.php route.

Web.php is the public-facing “browser” based route. This route is the most common and is what gets hit by the web browser. They run through the web middleware group and also contain facilities for CSRF protection (which helps defend against form-based malicious attacks and hacks) and generally contain a degree of “state” (by this I mean they utilize sessions).

91) How to generate a request in Laravel?

Use the following artisan command in Laravel to generate request:

php artisan make:request UploadFileRequest

About Author

Trackback 1

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email