Laravel Interview
Indoscie Technologies is Web Design and Development, SEO, PPC, Local Listing,
Adwords, E-mail Marketing, Digital Marketing service and solutions providers at a very affordable cost.
Following are frequently asked Laravel and PHP related interview questions for freshers as well as experienced candidates to get the right job.
1) What is Laravel?
Laravel is an open-source widely used PHP framework. The platform was intended for the development of web application by using MVC architectural pattern. Laravel is released under the MIT license.
Therefore, its source code is hosted on GitHub. It is a reliable PHP framework as it follows expressive and accurate language rules.
2) Define composer.
It is an application-level package manager for PHP. It provides a standard
format for managing PHP software dependencies and libraries.
3) What is HTTP middleware?
HTTP middleware is a technique for filtering HTTP requests. Laravel includes a middleware that checks whether application user is authenticated or not.
4) Name aggregates methods of query builder.
Aggregates methods of query builder are: 1) max(), 2) min(), 3) sum(), 4) avg(), and 5) count().
5) What is a Route?
A route is basically an endpoint specified by a URI (Uniform Resource Identifier). It acts as a pointer in Laravel application.
Most commonly, a route simply points
to a method on a controller and also dictates which HTTP methods are able to hit that URI.
6) Why use Route?
Routes are stored inside files under the /routes folder inside the project's root directory. By default, there are a few different files corresponding to the different "sides" of the application ("sides" comes from the hexagonal architecture methodology).
7) What do you mean by bundles?
In Laravel, bundles are referred to as packages. These packages are used to increase the functionality of Laravel. A package can have views, configuration, migrations, routes, and tasks.
8) Explain important
directories used in a common Laravel application.
Directories used in a common Laravel application are:
App/: This is a source folder where our application code lives. All controllers, policies, and models are inside this folder.
Config/: Holds the app's configuration files. These are usually not modified directly but instead, rely on the values set up in the .env (environment) file at the root of the app.
Database/: Houses the database files, including migrations, seeds, and test factories.
Public/: Publicly accessible folder holding compiled assets and of course an index.php file.
9) What is a
Controller?
A controller is the "C" in the "MVC" (Model-View-Controller) architecture, which is what Laravel is based on.
10) Explain reverse routing in Laravel.
Reverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible.
12) Explain traits in Laravel.
Laravel traits are a group of functions that you include within another class. A trait is like an abstract class. You cannot instantiate directly, but its methods can be used in concreate class.
13) Explain the concept of contracts in Laravel.
They are set of
interfaces of Laravel framework. These contracts provide core services. Contracts defined in Laravel include corresponding implementation of framework.
14) How will you register service providers?
You can register service providers in the config/app.php configuration file that contains an array where you can mention the service provider class name.
15) Where will you define Laravel's Facades?
All facades of Laravel have defined in IlluminateSupportFacades namespace.
16) State the difference between get and post method.
Get method allows you to send a limited amount of data in the
header. Post allows you to send a large amount of data in the body.
17) List default packages of Laravel 5.6.
Default packages of Laravel 5.6 are: 1) Envoy, 2) Passport, 3) Socialite, 4) Cashier, 5) Horizon, and 6) Scout.
18) What is service container in Laravel?
Service container is a tool used for performing dependency injection in Laravel.
19) How can you enable query log in Laravel?
You can use enableQueryLog method to enable query log in Laravel.
20) Explain the concept of events in Laravel.
An event is an occurrence or
action that help you to subscribe and listen for events that occur in Laravel application. Some of the events are fired automatically by Laravel when any activity occurs.
21) Explain dependency injection and their types.
It is a technique in which one object is dependent on another object. There are three types of dependency injection: 1) Constructor injection, 2) setter injection, and 3) interface injection.
22) What are the advantages of using Laravel?
Here are important benefits of Laravel:
Laravel has blade template engine to create dynamic layouts and increase compiling tasks.
Reuse code
without any hassle.
Laravel provides you to enforce constraints between multiple DBM objects by using an advanced query builder mechanism.
The framework has an auto-loading feature, so you don't do manual maintenance and inclusion paths
The framework helps you to make new tools by using LOC container.
Laravel offers a version control system that helps with simplified management of migrations.
23) Explain validation concept in Laravel.
Validations are an important concept while designing any Laravel application. It ensures that the data is always in an expected format before it stores into the database. Laravel provides many ways to validate
your data.
Base controller trait uses a ValidatesRequests class which provides a useful method to validate requests coming from the client machine.
24) What does ORM stand for?
ORM stands for Object Relational Mapping
25) How can you reduce memory usage in Laravel?
While processing a large amount of data, you can use the cursor method in order to reduce memory usage.
26) List available types of relationships in Laravel Eloquent.
Types of relationship in Laravel Eloquent are: 1) One To One 2) One To Many 3) Many To Many 4) Has Many Through, and 5) Polymorphic
Relations.
27) Name the Template Engine utilized by Laravel.
Blade is a powerful template engine utilized by Laravel.
28) Name databases supported by Laravel.
Laravel supports the following databases:
PostgreSQL
SQL Server
SQLite
MySQL
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 AppExceptionsHandler 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
SOURCE: https://www.guru99.com/laravel-interview-questions.html
################################### LARAVEL ################################################
A Quick Overview of
Laravel
Laravel Interview Questions
Laravel is a free and open-source PHP framework that follows the model–view–controller design (MVC) pattern. Our extensive collection of Laravel Interview Questions will help you find a great job. Laravel is a popular PHP framework that reduces the cost of development and improves code quality. Using Laravel, developers can save hours of development time and cut thousands of lines of code as compared to raw PHP. Because Laravel reuses the existing components of different frameworks in designing web applications, the outcome is more structured and pragmatic.
About Laravel What is Laravel Laravel is a free and
open-source PHP framework that follows the model–view–controller design pattern. Latest Version 6.0, released on 3rd September 2019. Created By Taylor Otwell Laravel Follows MVC architectural pattern Written in Laravel is written in the PHP language. Laravel Licence MIT License
Best Laravel Interview Questions And Answers
Q. 1.What is the laravel?
It is a free, powerful and open-source PHP framework that follows the model–view–controller design pattern. It is a very popular framework which is developed in PHP, and that reduces the cost of development and improves code quality. It is produced by Taylor Otwell. The first
version of laravel is released on 9 June 2011.
Features of Laravel
Eloquent ORM
Query builder available
Reverse routing
Restful controllers
Migrations
Database Seeding
Automatic pagination
Unit testing
Homestead
Is this helpful? Yes No
suggest an answer 0 Answer
235 22
Q. 2.What are the new features of Laravel 6?
The latest version 6.0 is incorporated with a number of latest features such as Laravel vapor compatibility, semantic visioning, job middleware, lazy collections, eloquent sub-query enhancements, Laravel users interface, etc. The Laravel 6.0 released on 3rd
September 2019 with latest and unique features.
Advanced Features of Laravel 6.0
Laravel Vapor Compatibility
Semantic Versioning
Job Middleware
Laravel User Interface (UI)
Eloquent Subquery Enhancements
Improved Authorization Responses
Lazy Collections
Also Read: What's new in laravel 6
Is this helpful? Yes No
suggest an answer 0 Answer
27 3
Q. 3.List the server requirements for Laravel 6?
PHP version >= 7.2.0
JSON PHP Extension
BCMath PHP Extension
Ctype PHP Extension
Mbstring PHP Extension
XML PHP Extension.
Tokenizer PHP
Extension
OpenSSL PHP Extension
PDO PHP Extension
Is this helpful? Yes No
suggest an answer 0 Answer
23 9
Q. 4.What are the steps to install Laravel with composer?
Laravel installation steps:-
Download composer from https://getcomposer.org/download (if you don’t have a composer on your system)
Open cmd
Goto your htdocs folder.
C:xampphtdocs>composer create-project laravel/laravel projectname
OR
If you install some particular version, then you can use
composer create-project laravel/laravel project name "5.6"
If you did not mention any particular version, then it will
install with the latest version.
Is this helpful? Yes No
suggest an answer 1 Answer
84 15
Q. 5.What is middleware in Laravel?
In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.
Example: If a user is not authenticated and it is trying to access the dashboard then, the middleware will redirect that user to the login page.
Get ready to be answerable to this
question. This is a favorite Laravel Interview Questions of many interviewers. Don’t let this question waste the opportunity. Read it twice.
Also Read: Importance of middleware in Laravel
Example
// Syntax
php artisan make:middleware MiddelwareName
// Example
php artisan make:middleware UserMiddelware
Now UserMiddelware.php file will create in
app/Http/Middleware
Is this helpful? Yes No
suggest an answer 0 Answer
99 5
Q. 6.What is Database Migration and how to use this in Laravel?
It is a type of version control for our database. It is allowing us to modify and share the application's database schema easily.
A migration file contains two methods up() and down().
up() is used to add new tables, columns, or indexes database and the down() is used
to reverse the operations performed by the up method.
Example
You can generate a migration & its file with the help of make:migration .
Syntax : php artisan make:migration blog
A current_date_blog.php file will be create in database/migrations
Is this helpful? Yes No
suggest an answer 0 Answer
50 4
Q. 7.What is reverse Routing in Laravel?
Reverse routing is generated URL’s based totally on route. It makes our application so a lot greater flexible.
Example
Route:: get(‘login’, ‘login@index’); // It is normal route but after reverse routing, we
can also call this link with
{{ HTML::link_to_action('login@index') }}
Is this helpful? Yes No
suggest an answer 1 Answer
32 17
Q. 8.How to pass CSRF token with ajax request?
In between head, tag put <meta name="csrf-token" content="{{ csrf_token() }}"> and in Ajax, we have to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Is this helpful? Yes No
suggest an answer 0 Answer
12 3
Q. 9.What is service providers?
In Laravel, service providers are the center of overall Laravel application bootstrapping. User applications, as well as core services of Laravel, are bootstrapped with service providers. These powerful tools are used by developers to manage class dependencies and perform dependency injection. To create a service provider, we have to use the below-mentioned artisan command.
You can use php artisan make: provider ClientsServiceProvider artisan command to generate a service provider
:
It has below listed functions in its file.
register function
boot function
Is this helpful? Yes No
suggest an answer 1 Answer
56 15
Q. 10.How to get data between two dates in Laravel?
In Laravel, we can use whereBetween() function to get data between two dates.
Example
Blog::whereBetween('created_at', [$dateOne, $dateTwo])->get();
Is this helpful? Yes No
suggest an answer 1 Answer
55 8
Q. 11.How to turn off CSRF protection for a particular route in Laravel?
We can add that particular URL or Route in $except variable. It is present in the appHttpMiddlewareVerifyCsrfToken.php file.
Example
class VerifyCsrfToken extends
BaseVerifier {
protected $except = [
'Pass here your URL',
];
}
Is this helpful? Yes No
suggest an answer 0 Answer
51 8
Q. 12.How to use Stored Procedures in Laravel?
How to create a Stored Procedure
To create a Stored Procedure you can execute given code in your MySQL query builder
directly or use phpmyadmin for this.
DROP PROCEDURE IF EXISTS `get_subcategory_by_catid`;
delimiter ;;
CREATE PROCEDURE `get_subcategory_by_catid` (IN idx int)
BEGIN
SELECT id, parent_id, title, slug, created_at FROM category WHERE parent_id = idx AND status = 1 ORDER BY title;
END
;;
delimiter ;
After this, you can use this created procedure in your code in Laravel.
How to use stored procedure in Laravel
$getSubCategories = DB::select(
'CALL get_subcategory_by_catid('.$item->category_id.')'
);
Is this helpful? Yes No
suggest an
answer 1 Answer
30 21
Q. 13.What is Facade and how it can be used in Laravel?
In Laravel, Facades offer a static interface to classes available inside the application's service container. They serve as static proxies for underlying classes present in the service container, offering benefit of expressive syntax while maintaining more flexibility and testability than other available traditional static methods.
All the facades are defined in the namespace IlluminateSupportFacades for easy accessibility and usability.
Example
use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('PutkeyNameHere');
});
Is this helpful? Yes No
suggest an answer 0 Answer
24 12
Q.
14.What is the use of dd() in Laravel?
It is a helper function which is used to dump a variable's contents to the browser and stop the further script execution. It stands for Dump and Die.
Example
dd($array);
Is this helpful? Yes No
suggest an answer
0 Answer
39 7
Q. 15.How to make a helper file in laravel?
We can create a helper file using Composer. Steps are given below:-
Please create a "app/helpers.php" file that is in app folder.
Add
"files": [
"app/helpers.php"
]
in "autoload" variable.
Now update your composer.json with composer dump-autoload or composer update
Is this helpful? Yes No
suggest an answer 0 Answer
28 9
Q. 16.What is PHP artisan in laravel? Name some common artisan commands?
Artisan is a type of the "command line interface" using in Laravel. It provides lots of helpful
commands for you while developing your application. We can run these command according to our need.
Laravel supports various artisan commands like
php artisan list;
php artisan –version
php artisan down;
php artisan help;
php artisan up;
php artisan make:controller;
php artisan make:mail;
php artisan make:model;
php artisan make:migration;
php artisan make:middleware;
php artisan make:auth;
php artisan make:provider etc.;
Is this helpful? Yes No
suggest an answer 0 Answer
27 4
Q. 17.How to create custom validation rules with Laravel?
Run this
"php artisan make:rule OlympicYear"
After that command it generates a file app/Rules/OlympicYear.php
We can write rule in the passes() in OlympicYear.php generated file. It will return true or false depending on condition, which is this in our case
public function passes($attribute, $value)
{
return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
}
Next, we can update error message to be this:
public function message()
{
return ':attribute should be a year of Olympic Games';
}
Finally, we use this class in controller's store() method we have this code:
public function store(Request
$request)
{
$this->validate($request, ['year' => new OlympicYear]);
}
Is this helpful? Yes No
suggest an answer 0 Answer
14 5
Q. 18.What is the difference between {{ $username }} and {!! $username !!} in Laravel?
{{ $username }} is simply used to display text contents but {!! $username !!} is used to display content with HTML tags if exists.
Is this helpful? Yes No
suggest an answer 1 Answer
42 6
Q. 19.What is laravel Service container?
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection.
It is also known as the IoC container. It offers several benefits to users such as.
Advantages of Service Container
Freedom to manage class dependencies on object creation.
Service contain as Registry.
Ability to bind interfaces to concrete classes.
Also Read: Benefits of Laravel Over Other PHP Frameworks
Is this helpful? Yes No
suggest an answer 0 Answer
14 5
Q. 20.How to use session in laravel?
1. Retrieving Data from session
session()->get('key');
2. Retrieving All session data
session()->all();
3. Remove data from
session
session()->forget('key'); or session()->flush();
4. Storing Data in session
session()->put('key', 'value');
Is this helpful? Yes No
suggest an answer 0 Answer
30 3
Q. 21.How to get last inserted id using laravel query?
In case you are using save()
$blog = new Blog;
$blog->title = ‘Best Interview Questions’;
$blog->save()
// Now you can use (after save() function we can use like this)
$blog->id // It will display last inserted id
In case you are using insertGetId()
$insertGetId
= DB::table(‘blogs’)->insertGetId([‘title’ => ‘Best Interview Questions’]);
Is this helpful? Yes No
suggest an answer 0 Answer
15 5
Q. 22.How to use mail() in laravel?
Laravel provides a powerful and clean API over the SwiftMailer library with drivers for Mailgun, SMTP, Amazon SES, SparkPost, and send an email. With this API, we can send email on a local server as well as the live server.
Here is an example through the mail()
Laravel allows us to store email messages in our views files. For example, to manage our emails, we can create an email directory
within our resources/views directory.
Example
public function sendEmail(Request $request, $id)
{
$user = Admin::find($id);
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
$m->from('info@bestinterviewquestion.com', 'Reminder');
$m->to($user->email, $user->name)->subject('Your Reminder!');
});
}
Is this helpful? Yes No
suggest an answer 0 Answer
12 3
Q. 23.How to use cookies in laravel?
1. How to set Cookie
To set cookie value, we have to use Cookie::put('key', 'value');
2. How to get Cookie
To get cookie Value we have to use Cookie::get('key');
3. How to delete
or remove Cookie
To remove cookie Value we have to use Cookie::forget('key')
4. How to check Cookie
To Check cookie is exists or not, we have to use Cache::has('key')
Is this helpful? Yes No
suggest an answer 0 Answer
14 3
Q. 24.What is Auth? How is it used?
Laravel Auth is the process of identifying the user credentials with the database. Laravel managed it's with the help of sessions which take input parameters like username and password, for user identification. If the settings match then the user is said to be authenticated.
Auth is in-built functionality provided by
Laravel; we have to configure.
We can add this functionality with php artisan make: auth
Auth is used to identifying the user credentials with the database.
Is this helpful? Yes No
suggest an answer 0 Answer
23 4
Q. 25.How to make a constant and use globally?
You can create a constants.php page in config folder if does not exist. Now you can put constant variable with value here and can use with Config::get('constants.VaribleName');
Example
return [
'ADMINEMAIL' => 'info@bestinterviewquestion.com',
];
Now we can display with
Config::get('constants.ADMINEMAIL');
Is this helpful? Yes No
suggest an answer 0 Answer
18 1
Q. 26.What are the difference between laravel 4 and 5?
There are sizable differences between
laravel 4 and laravel 5 concerning LTS, features, file structures, etc.
Laravel four used to be the one who delivered large reputation to the Laravel framework, however this version no longer up to date anymore, and it also lacks a lot of functions released in Laravel 5.
Laravel 4 released May 2013 however Laravel 5 released in February 2015.
Laravel 5 has LTS Supports. It capability the LTS version stands for Long Term Support. It implies that bugfixes for that model will be provided for two years, till the next LTS version.
A new listing app/Providers replaces the app/start archives from preceding versions of Laravel 4.x.
Laravel 5 offers a
Socialite bundle which is an optional, Laravel 5.0+ well matched package that provides painless authentication with OAuth providers.
The favored dd helper function, which dumps variable debug information, has been upgraded to use the incredible Symfony VarDumper.
In distinction to Laravel four to 5 version differences, which is huge, 5.x and 5.y variations are now not that different. Some features added, some updated/removed in laravel 5, but the core structure stays the same.
Is this helpful? Yes No
suggest an answer 0 Answer
4 5
Q. 27.What is with() in Laravel?
with() function is used to eager load in Laravel.
Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
Is this helpful? Yes No
suggest an answer 1 Answer
5 2
Q. 28.How to remove /public from URL in laravel?
You can do this in various ways. Steps are given below:-
Copy .htaccess file from public folder and now paste it into your root.
Now rename server.php file/page to index.php on your root folder.
Now you can remove /public word from URL and
refresh the page. Now it will work.
Is this helpful? Yes No
suggest an answer 2 Answer
17 4
Q. 29.How to use joins in laravel?
Laravel supports various joins that's are given below:-
Inner Join
DB::table('admin') ->join('contacts', 'admin.id', '=', 'contacts.user_id') ->join('orders', 'admin.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price') ->get();
Left Join / Right Join
$users = DB::table('admin') ->leftJoin('posts', 'admin.id', '=', 'posts.admin_id') ->get();
$users = DB::table('admin') ->rightJoin('posts', 'admin.id', '=',
'posts.admin_id') ->get();
Cross Join
$user = DB::table('sizes') ->crossJoin('colours') ->get();
Advanced Join
DB::table('admin') ->join('contacts', function ($join) { $join->on('admin.id', '=', 'contacts.admin_id')->orOn(...); }) ->get();
Sub-Query Joins
$admin = DB::table('admin') ->joinSub($latestPosts, 'latest_posts', function ($join) { $join->on('admin.id', '=', 'latest_posts.admin_id'); })->get();
Is this helpful? Yes No
suggest an answer 0 Answer
9 1
Q. 30.How to get user’s ip address in laravel?
You can use
request()->ip()
You can also use : Request::ip() but in this case we have to call namespace like this : Use IlluminateHttpRequest;
Is this helpful? Yes No
suggest an answer 0 Answer
21 6
Q. 31.What are the difference between softDelete() & delete() in Laravel?
1. delete()
In case when we used to delete in Laravel then it removed records from the database table.
Example:
$delete = Post::where(‘id’, ‘=’, 1)->delete();
2. softDeletes()
To delete records permanently is not a good thing that’s why laravel used
features are called SoftDelete. In this case, records did not remove from the table only delele_at value updated with current date and time.
Firstly we have to add a given code in our required model file.
use SoftDeletes;
protected $dates = ['deleted_at'];
After this, we can use both cases.
$softDelete = Post::where(‘id’, ‘=’, 1)->delete();
OR
$softDelete = Post::where(‘id’, ‘=’, 1)->softDeletes();
Is this helpful? Yes No
suggest an answer 5 Answer
18 2
Q. 32.How to enable query log
in laravel?
Our first step should be
DB::connection()->enableQueryLog();
After our query, it should be placed
$querieslog = DB::getQueryLog();
After that, it should be placed
dd($querieslog)
You can also read: Laravel 5 Interview Questions
Example
DB::connection()->enableQueryLog();
$result = User:where(['status' =>
1])->get();
$log = DB::getQueryLog();
dd($log);
Is this helpful? Yes No
suggest an answer 0 Answer
19 1
Q. 33.How to upload files in laravel?
We have to call Facades in our controller file with this :
use IlluminateSupportFacadesStorage;
Example
if($request->hasFile(file_name')) {
$file = Storage::putFile('YOUR FOLDER PATH', $request->file('file_name'));
}
Is this helpful? Yes No
suggest an answer 0 Answer
12 7
Q. 34.How to use soft delete in laravel?
Soft delete is a laravel feature that helps When models are
soft deleted, they are not actually removed from our database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, we have to specify the soft delete property on the model like this.
In model we have to use namespace
use IlluminateDatabaseEloquentSoftDeletes;
and we can use this
use SoftDeletes; in our model property.
After that when we will use delete() query then records will not remove from our database. then a deleted_at timestamp is set on the record.
Is this helpful? Yes No
suggest an answer 0 Answer
15 4
Q. 35.What is
Eloquent ORM in Laravel?
The Eloquent ORM present in Laravel offers a simple yet beautiful ActiveRecord implementation to work with the database. Here, each database table offers a corresponding model which is used to interact with the same table. We can create Eloquent models using the make:model command.
It has many types of relationships.
One To One relationships
One To Many relationships
Many To Many relationships
Has Many Through relationships
Polymorphic relationships
Many To Many Polymorphic relationships
For more details you can visit www.Laravel.com
Is this helpful? Yes No
suggest
an answer 0 Answer
15 4
Q. 36.What is composer lock in laravel?
After running the composer install in the project directory, the composer will generate the composer.lock file.It will keep a record of all the dependencies and sub-dependencies which is being installed by the composer.json.
Is this helpful? Yes No
suggest an answer 1 Answer
6 1
Q. 37.How to enable or disable maintenance mode in Laravel?
We have to use the following artisan commands to enable/disable maintenance mode.
Enable maintenance mode
php artisan down
Disable maintenance
mode
php artisan up
Is this helpful? Yes No
suggest an answer 0 Answer
9 3
Q. 38.What is Dependency injection in Laravel?
In Laravel, dependency injection is a term used for the activity of injecting components into the user application. It’s a key element of agile architecture. The Laravel service container is a powerful tool that manages all class dependencies and performs dependency injection.
public function __construct(UserRepository $data)
{
$this->userdata = $data;
}
In this given an example, the UserController needs to retrieve users data from a
data source(database). So, we can inject a service that is able to recover all users. In this example, our UserRepository most likely uses Eloquent to get user’s data from the database.
Is this helpful? Yes No
suggest an answer 1 Answer
11 4
Q. 39.Which template engine laravel use?
Laravel uses "Blade Template Engine". It is a straightforward and powerful templating engine that is provided with Laravel.
Is this helpful? Yes No
suggest an answer 0 Answer
11 3
Q. 40.How to create real time sitemap.xml file in Laravel?
We can create all web pages of our sites to tell Google and other search engines like Bing, Yahoo etc about the organization of our site content. These search engine web crawlers read this file to more intelligently crawl our sites.
Here are the steps that helps you to create real time sitemap.xml file and these steps also helps to create dynamic XML files.
Firstly we have to create a route for this in your routes/web.php file
Example
Route::get('sitemap.xml', 'SitemapController@index')->name('sitemapxml');
Now you can create SitemapController.php with artisan command php artisan
make:controller SitemapController
Now you can put this code in your controller
public function index() {
$page = Page::where('status', '=', 1)->get();
return response()->view('sitemap_xml', ['page' => $page])->header('Content-Type', 'text/xml');
}
Now please create a view file in resources/view/sitemap_xml.blade.php file with this code
Put this code in that created view file
'; ?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
@foreach ($page as $post)
{{ url($post->page_slug) }}
{{ $post->updated_at->tz('UTC')->toAtomString() }}
0.9
@endforeach
You can also read: How to generate pdf in laravel
Is this helpful? Yes No
suggest an answer 0 Answer
7 2
Q. 41.How to use aggregate functions in Laravel?
Laravel provides a variety of aggregate functions such as max, min, count,avg, and sum. We can call any of these functions after constructing our
query.
$users = DB::table(‘admin’)->count();
$maxComment = DB::table(‘blogs’)->max('comments');
Is this helpful? Yes No
suggest an answer 0 Answer
6 3
Q. 42.How to use skip() and take() in Laravel Query?
We can use skip() and take() both methods to limit the number of results in the query. skip() is used to skip the number of results and take() is used to get the number of result from the query.
Example
$posts = DB::table('blog')->skip(5)->take(10)->get();
// skip first 5 records
// get 10 records after 5
Is this helpful? Yes No
suggest an answer 0 Answer
13 3
Q. 43.What design patterns used for Laravel Framework?
Design patterns are not prepared instructions or libraries, that can be definitely utilized to your system,
this is no longer a concrete solution that can be converted into source code, plan patterns are an awful lot greater than that. They are patterns or templates, that can be carried out to resolve a problem in different particular situations.
Design Patterns in Laravel
The Builder pattern
The Repository pattern
The need for the Builder pattern
The need for the Factory pattern
The Factory pattern
The Provider pattern
The Facade pattern
The Strategy pattern
The need for the Repository pattern etc
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 44.What is Repository
pattern in laravel?
It allows using objects without having to know how these objects are persisted. It is an abstraction of the data layer. It means that our business logic no need to know how data is retrieved. The business logic relies on the repository to get the correct data.
Basically it is used to decouple the data access layers and business logic in our application.
Is this helpful? Yes No
suggest an answer 0 Answer
4 1
Q. 45.What is Vapor in Laravel?
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 46.What is Singleton design pattern in
laravel?
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 47.What is laravel contract?
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 48.What is authorization in laravel?
Is this helpful? Yes No
suggest an answer 0 Answer
2 3
Q. 49.How to rollback a particular migration in laravel?
Is this helpful? Yes No
suggest an answer 0 Answer
2 3
Q. 50.Which is better CodeIgniter or Laravel?
Is this helpful? Yes No
suggest an answer 0 Answer
2
3
Q. 51.How to run job queue through command line in laravel?
You can run this Artisan Command php artisan queue:work --tries=3 OR --once --queue=JobQueueName
You can use both --tries or --once. When you will use --once then you command will execute singly and when you will use --tries=2 the it will execute two times and further.
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 52.What are views?
Views contain the HTML provided by our application and separate our controller or application logic from our presentation logic. These are stored in the resources/views
directory.
Related Article: HTML5 Questions And Answers
Example
<html>
<body>
<h1>Best Interview Question<h1>
</body>
</html>
Is this helpful? Yes No
suggest an answer 0 Answer
8 2
Q. 53.What is faker in Laravel?
Faker is a type of module or packages which are used to create fake data for testing purposes. It can be used to produce all sorts of data.
It is used to generate the given data types.
Lorem text
Numbers
Person i.e. titles, names, gender, etc.
Addresses
DateTime
Phone numbers
Internet i.e. domains, URLs, emails etc.
Payments
Colour, Files, Images
UUID, Barcodes, etc
In Laravel, Faker is used
basically for testing purposes.
Is this helpful? Yes No
suggest an answer 0 Answer
7 2
Q. 54.What are the advantages of Queue?
In Laravel, Queues are very useful for taking jobs, pieces of asynchronous work, and sending them to be performed by other processes and this is useful when making time-consuming API calls that we don’t want to make your users wait for before being served their next page.
Another advantage of using queues is that you don’t want to work the lines on the same server as your application. If your jobs involve intensive computations, then you don’t want to take risk those jobs
taking down or slowing your web server.
Is this helpful? Yes No
suggest an answer 0 Answer
9 3
Q. 55.What is tinker in laravel?
Laravel Tinker is a powerful REPL tool which is used to interact with Laravel application with the command line in an interactive shell. Tinker came with the release of version 5.4 is extracted into a separate package.
How to install tinker
composer require laravel/tinker
How to execute
To execute tinker we can use php artisan tinker command.
Is this helpful? Yes No
suggest an answer 3 Answer
9 5
Q.
56.How to clear complete cache in Laravel?
Please run below artisan commands step wise step.
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear
Is this helpful? Yes No
suggest an answer 0 Answer
11 3
Q. 57.What is seed in laravel?
Laravel offers a tool to include dummy data to the database automatically. This process is called seeding. Developers can add simply testing data to their database table using the database seeder. It is extremely useful as testing with various data types allows developers to detect bugs and
optimize performance. We have to run the artisan command make:seeder to generate a seeder, which will be placed in the directory database/seeds as like all others.
How to create database seeder
To generate a seeder, run the make:seeder Artisan command. All seeders generated by the laravel will be placed in the database/seeds directory:
php artisan make:seeder AdminTableSeeder
Is this helpful? Yes No
suggest an answer 0 Answer
8 2
Q. 58.What is a REPL?
REPL is a type of interactive shell that takes in single user inputs, process them, and returns the result to the
client.
The full form of REPL is Read—Eval—Print—Loop
Is this helpful? Yes No
suggest an answer 0 Answer
4 1
Q. 59.How to use update query in Laravel?
With the help of update() function, we can update our data in the database according to the condition.
Example
Blog::where(['id' => $id])->update([
'title' => ’Best Interview
Questions’,
‘content’ => ’Best Interview Questions’
]);
OR
DB::table("blogs")->where(['id' => $id])->update([
'title' => ’Best Interview Questions’,
‘content’ => ’Best Interview Questions’
]);
Is this helpful? Yes No
suggest an answer 0 Answer
8 4
Q. 60.How to use multiple OR condition in Laravel Query?
Blog::where(['id' => 5])->orWhere([‘username’ => ‘info@bestinterviewquestion.com’])->update([
'title' => ‘Best Interview Questions’,
]);
Is this helpful? Yes No
suggest an answer 0 Answer
8 3
Q. 61.Please write some additional where Clauses in Laravel?
Laravel provides various methods that we can use in queries to get records with our conditions.
These methods
are given below
where()
orWhere()
whereBetween()
orWhereBetween()
whereNotBetween()
orWhereNotBetween()
wherein()
whereNotIn()
orWhereIn()
orWhereNotIn()
whereNull()
whereNotNull()
orWhereNull()
orWhereNotNull()
whereDate()
whereMonth()
whereDay()
whereYear()
whereTime()
whereColumn()
orWhereColumn()
whereExists()
Is this helpful? Yes No
suggest an answer 0 Answer
7 4
Q. 62.How to use updateOrInsert() method in Laravel Query?
updateOrInsert() method is used to update an existing record in the database if
matching the condition or create if no matching record exists.
Its return type is Boolean.
Syntax
DB::table(‘blogs’)->updateOrInsert([Conditons],[fields with value]);
Example
DB::table(‘blogs’)->updateOrInsert(
['email' => 'info@bestinterviewquestion.com', 'title' => 'Best Interview Questions'],
['content' => 'Test
Content']
);
Is this helpful? Yes No
suggest an answer 0 Answer
13 1
Q. 63.How to check table is exists or not in our database using Laravel?
We can use hasTable() to check table exists in our database or not.
Syntax
Schema::hasTable('users'); // here users is the table name.
Example
if(Schema::hasTable('users')) {
// table is exists
} else {
// table is not exists
}
Is this helpful? Yes No
suggest an answer 0 Answer
7 1
Q. 64.How to check column is exists or not in a table using Laravel?
if(Schema::hasColumn('admin', 'username'))
; //check whether admin table has username column
{
// write your logic here
}
Is this helpful? Yes No
suggest an answer 0 Answer
7 2
Q. 65.What are the difference between insert() and insertGetId() in laravel?
Inserts(): This method is used for insert records into the database table. No need the “id†should be autoincremented or not in the table.
Example
DB::table('bestinterviewquestion_users')->insert(
['title' => 'Best Interview Questions', 'email' =>
‘info@bestinterviewquestion.com’]
);
It will return true or false.
insertGetId(): This method is also used for insert records into the database table. This method is used in the case when an id field of the table is auto incrementing.
It returns the id of current inserted records.
Example
$id = DB::table('bestinterviewquestion_users')->insert(
['title' => 'Best Interview Questions', 'email' => ‘info@bestinterviewquestion.com’]
);
Is this helpful? Yes No
suggest an answer 2
Answer
9 1
Q. 66.What is the use of Accessors and Mutators in Eloquent ?
Laravel accessors and mutators are customs, user-defined methods that allow you to format Eloquent attributes. Accessors are used to format attributes when you retrieve them from the database.
1. Defining an accessor
The syntax of an accessor is where getNameAttribute() Name is capitalized attribute you want to access.
public function getNameAttribute($value)
{
return ucfirst($value);
}
2. Defining a mutator
Mutators format the attributes before saving them to the
database.
The syntax of a mutator function is where setNameAttribute() Name is a camel-cased column you want to access. So, once again, let’s use our Name column, but this time we want to make a change before saving it to the database:
public function setNameAttribute($value)
{
$this->attributes['name'] = ucfirst($value);
}
Is this helpful? Yes No
suggest an answer 0 Answer
8 3
Q. 67.How to change your default database type in Laravel?
Please update 'default' => env('DB_CONNECTION', 'mysql'), in config/database.php. Update MySQL as a database
whatever you want.
Is this helpful? Yes No
suggest an answer 0 Answer
8 2
Q. 68.Explain Closures in laravel?
In Laravel, a closure is an anonymous function that often used as callback methods. Developers can also use it as a parameter in a function.
Example
function handle(Closure $closure) {
$closure();
}
handle(function(){
echo ‘Best Interview Question’;
});
We can start by adding a Closure parameter to the handle method. This will be used as type hint us that the handle method takes a Closure.
We can call the handle method and pass a service as a parameter.
By using $closure(); in the handle method we tell Laravel to execute the given Closure which will then display ‘Best Interview
Question.’
Is this helpful? Yes No
suggest an answer 0 Answer
3 6
Q. 69.What is the latest version of laravel?
The latest version of Laravel is 6.0. It released on 3rd September 2019.
Is this helpful? Yes No
suggest an answer 0 Answer
26 10
Q. 70.What are the basic concepts in laravel?
These are the most important concepts used in Laravel
Blade
Templating
Routing
Eloquent ORM
Middleware
Artisan(Command-Line Interface)
Security
In built Packages
Caching
Service Providers
Facades
Service Container
Is this helpful? Yes No
suggest an answer 0 Answer
13 6
Q. 71.What is eager loading in Laravel?
Eager loading is used when we have to fetch some useful data along with the data which we want from the database. We can eager load in laravel using the load() and with() commands.
Is this helpful? Yes No
suggest an answer 1 Answer
5 2
Q. 72.How to get table name from model
in Laravel 5?
If we want to get a table in Laravel application from a particular Model then we can use getTable() method.
Example
$user = new BestInterviewQuestions;
$tableName = $user->getTable();
print_r($tableName);
Is this
helpful? Yes No
suggest an answer 0 Answer
0 4
Q. 73.What is lumen?
Lumen is a newly introduced micro PHP framework which is a faster, smaller and leaner version of a full web application framework. It is introduced by Taylor Otwell, the creator of Laravel. It uses the same components as Laravel, but especially for microservices.
It has a simple installer like Laravel. You have to use this command to install lumen.
composer global require "laravel/lumen-installer=~1.0"
Is this helpful? Yes No
suggest an answer 0 Answer
6 5
Q. 74.How to upgrade form laravel 5
to laravel 6?
Open the laravel project inside the code editor.
Go to the Composer.json file and change the laravel/framework from 5 to 6.
Open the terminal and write the command – composer update and hit enter to wait for the update to complete.
After finished run the server command (PHP artisan serve) and run the project in a browser.
After this , again go to terminal and write command –(composer require laravel/ui) and hit enter and download the packages.
Then, for creating the auth file write the command ( PHP artisan ui vue-auth) to make the auth file in laravel 6.0.
In this way, we can upgrade from laravel 5 to laravel
6.
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 75.How to know laravel version?
You can use an artisan command php artisan --version to know the laravel version.
Is this helpful? Yes No
suggest an answer 2 Answer
2 3
Q. 76.Why laravel is the best PHP framework in 2019?
Easy Installation
Supports MVC Architecture
Ensures high security
Modular Design
Object-Oriented Libraries
Is this helpful? Yes No
suggest an answer 0 Answer
2 3
Q. 77.How do I stop Artisan serve in
Laravel?
We can do it with 3 simple steps.
Press Ctrl + Shift + ESC. Locate the php system walking artisan and kill it with proper click -> kill process.
Reopen the command-line and begin again the server.
Note that you ought to be able to kill the manner just by using sending it a kill sign with Ctrl + C.
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 78.How to generate application key in laravel?
You can use php artisan key:generate to generate your application key.
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q.
79.What is LTS version of Laravel?
LTS Stands for Long Term Support. LTS variations get hold of bug fixes for two years, and protection fixes for three years. General minor releases handle bug fixes for six months and protection fixes for one year. Laravel 5.5 is the next long-time period support (LTS) version of Laravel.
Is this helpful? Yes No
suggest an answer 0 Answer
2 3
Q. 80.How to use GROUP_CONCAT() with JOIN in Laravel?
Here is an example to understand the concept of using group_concat() to join in Laravel. We have 3 tables like "dynamic_forms", "dynamic_forms_mapping",
"categories".
Example
$list = DB::table('dynamic_forms')
->select("dynamic_forms.*" ,DB::raw("(GROUP_CONCAT(wf_categories.name SEPARATOR ', ')) as category"))
->leftjoin("dynamic_forms_mapping", "dynamic_forms_mapping.form_id","=","dynamic_forms.id")
->leftjoin("categories", "dynamic_forms_mapping.category_id","=","categories.id")
->groupBy('dynamic_forms.id')
->where('dynamic_forms.status', 1)
->get();
Is this helpful? Yes No
suggest an answer 0 Answer
1 3
Q. 81.How to extend login expire time in Auth?
You can extend the login expire time with configsession.php this file location. Just update lifetime the variables value. By default it is 'lifetime' => 120. According
to your requirement update this variable.
Example
'lifetime' => 180
Is this helpful? Yes No
suggest an answer 0 Answer
5 2
Q. 82.How can we use middleware in laravel?
It acts as a middleman between a request and a response.
Middleware is a type of filtering mechanism used in Laravel application.
We can create middelware with
php artisan make:middleware UsersMiddleware
Here "UsersMiddleware" is the name of Middleware. After this command a "UsersMiddleware.php" file created in app/Http/Middleware directory.
After that we have to register that middleware in kernel.php (available in app/Http directory) file in "$routeMiddleware" variable.
'Users' => AppHttpMiddlewareUsersMiddleware::class,
Now we can call "Users" middleware where we need it like controller or route file.
We can use it in controller file like this.
public function __construct()
{
$this->middleware('Users');
}
In route file we can use like this.
Route::group(['middleware' => 'Users'], function () {
Route::get('/', 'HomeController@index');
});
Is this helpful? Yes No
suggest an answer 0 Answer
9 1
Q. 83.How to register service provider in laravel?
All the service providers get registered in the configuration file known as config/app.php. This is the file that contains the provider's array and here the user is able to list all the class names for the respective service providers. And by default, the set of service providers of Laravel core are listed inside this array. Now,
these services providers bootstrap all the Laravel components that are core, like the mailer, cache, queue, and others. So, to register a required provider, add that provider to the array:
'providers' => [
// Other Service Providers
AppProvidersComposerServiceProvider::class,
],
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 84.What is the full form of ORM in Laravel?
ORM Stands for Object Relational Mapping.
Is this helpful? Yes No
suggest an answer 0 Answer
1 3
Q. 85.What is Implicit
Controller in Laravel?
It allows us to easily define a single route to handle all activities in a controller. We can define the route using the Route::controller method:
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 86.What is Listeners in Laravel?
Listeners handle each and every activity that is mentioned in the event being registered. An artisan command which is event: generate creates all of the listeners inside the app/listeners directory. This Listeners folder holds a file namely “EventListener.php “ that has every single method required to handle
listeners.
Example
EventListener.php
namespace AppListeners;
use AppEventsSomeEvent;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
class EventListener{
public function __construct() {
//
}
public function handle(SomeEvent $event) {
//
}
}
As mentioned above in this code, it involves the handle function to manage various events. Also, we can build several independent listeners which will target one single event.
Is this helpful? Yes No
suggest an answer 0 Answer
0 4
Q. 87.What are the features of
laravel?
Offers a rich set of functionalities like Eloquent ORM, Template Engine, Artisan, Migration system for databases, etc
Libraries & Modular
It supports MVC Architecture
Unit Testing
Security
Website built in Laravel is more scalable and secure.
It includes namespaces and interfaces that help to organize all resources.
Provides a clean API.
Is this helpful? Yes No
suggest an answer 0 Answer
6 1
Q. 88.What are gates in laravel?
Laravel Gate holds a sophisticated mechanism that ensures the users that they are authorized for performing actions on the resources. The implementation of
the models is not defined by Gate. This renders the users the freedom of writing each and every complex spec of the use case that a user has in any way he/she wishes. Moreover, the ACL packages can be used as well with the Laravel Gate. With the help of Gate, users are able to decouple access logic and business logic. This way clutter can be removed from the controllers.
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 89.How to rollback last migration in laravel?
You can use php artisan migrate:rollback --step=1.
Also Read: Importance of Database Migration in Laravel
Is this helpful?
Yes No
suggest an answer 0 Answer
2 2
Q. 90.What is Package in laravel? Name some laravel packages?
Developers use packages to add functionality to Laravel. Packages can be almost anything, from great workability with dates like Carbon or an entire BDD testing framework such as Behat. There are standalone packages that work with any PHP frameworks, and other specially interned packages which can be only used with Laravel. Packages can include controllers, views, configuration, and routes that can optimally enhance a Laravel application.
There are many packages are available nowadays also laravel has some official packages
that are given below:-
Cashier
Dusk
Envoy
Passport
Socialite
Scout
Telescope etc
Is this helpful? Yes No
suggest an answer 0 Answer
5 2
Q. 91.What is forge in Laravel?
Forge in Laravel is one tool that is used for deploying as well as configuring numerous web applications. This was created by the developers of the renowned Laravel framework, though this can be utilized for automating the deployment-related to any of the web application on the condition that these applications use the PHP server. Forge in Laravel automates each and every necessary installation as well as configuration step, which
enables users to get their website up along with running quickly.
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 92.What is validation in laravel and how it is used?
Validation is a most important thing while designing an application. It validates the incoming data. It uses ValidatesRequests trait which provides a convenient method to authenticate incoming HTTP requests with powerful validation rules.
Here are some Available Validation Rules in Laravel are listed:-
Alpha
Image
Date Format
IP Address
URL
Numeric
Size
Min ,
Max
Unique with database etc
Is this helpful? Yes No
suggest an answer 0 Answer
5 2
Q. 93.Is laravel good for API?
Laravel is an appropriate choice for PHP builders to use for building an API, especially when a project’s necessities are not exactly defined. It's a comprehensive framework suitable for any type of application development, is logically structured, and enjoys robust community support.
Laravel includes factors for not solely API development, but front-end templating and singe-page software work, and other aspects that are totally unrelated to only building a net utility
that responds to REST Http calls with JSON.
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 94.How to extend a layout file in laravel view?
With this @extends('layouts.master') we can extend this master layout in any view file.
In this example layouts are a folder that is placed in resources/views available and the master file will be there. Now "master.blade.php" is a layout file.
These laravel questions will help you to crack your future interviews.
Is this helpful? Yes No
suggest an answer 0 Answer
6 3
Q. 95.How to
redirect form controller to view file in laravel?
We can use
return redirect('/')->withErrors('You can type your message here');
return redirect('/')->with('variableName', 'You can type your message here');
return redirect('/')->route('PutRouteNameHere');
Is this helpful? Yes No
suggest an answer 0 Answer
6 1
Q. 96.How to use Ajax in any form submission?
Example
<script
type="text/javascript">
$(document).ready(function() {
$("FORMIDORCLASS").submit(function(e){
// FORMIDORCLASS will your your form CLASS ot ID
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
// you have to pass in between tag
}
})
var formData = $("FORMIDORCLASS").serialize();
$.ajax({
type: "POST",
url: "",
data : formData,
success: function( response ) {
// Write here your sucees message
}, error: function(response) {
// Write here your error message
},
});
return false;
});
});
</script>
Is this helpful? Yes No
suggest an answer 0 Answer
5 5
Q. 97.How to get current route
name?
request()->route()->getName()
Is this helpful? Yes No
suggest an answer 0 Answer
6 1
Q. 98.How to create model controller and migration in a single artisan command in Laravel?
php artisan make:model ModelNameEnter -mcr
Is this helpful? Yes No
suggest an answer 1 Answer
7 4
Q. 99.How to pass multiple variables by controller to blade file?
$valiable1 = 'Best';
$valiable2 = 'Interview';
$valiable3 = 'Question';
return view('frontend.index', compact('valiable1', valiable2',
valiable3'));
In you View File use can display by {{ $valiable1 }} or {{ $valiable2 }} or {{ $valiable3 }}
Is this helpful? Yes No
suggest an answer 0 Answer
3 3
Q. 100.How to override a Laravel model's default table name?
We have to pass protected $table = 'YOUR TABLE NAME'; in your respective Model
You can also read: Mysql Interview Questions
Example
namespace
App;
use IlluminateDatabaseEloquentModel;
class Login extends Model
{
protected $table = 'admin';
static function logout() {
if(session()->flush() || session()->regenerate()) {
return true;
}
}
}
Is this helpful? Yes No
suggest an answer 0 Answer
6 3
Q. 101.How to set a global variable for all views?
For this you have to get value & assign value in controller file in __construct() like this.
Example
public function __construct() {
$this->middleware(function
($request, $next) {
$name = session()->get('businessinfo.name'); // get value from session
View::share('user_name', $name); // set value for all View
View::share('user_email', session()->get('businessinfo.email'));
return $next($request);
});
}
Is this helpful? Yes No
suggest an answer 0 Answer
1 4
Q. 102.How to use Where null and Where not null eloquent query in Laravel?
Where Null Query
DB::table('users')->whereNull('name')->get();
Where Not Null Query
DB::table('users')->whereNotNull('name')->get();
Is this helpful? Yes No
suggest an answer 0 Answer
6
3
Q. 103.What is ACL in laravel?
ACL Stands for Access Control List.
If you needed to control get entry to certain sections of the site, or flip on or off unique portions of a web page for non-admins, or ensure any person can only edit their very own contacts, you wanted to deliver in a device like BeatSwitch Lock or hand-roll the functionality, which would be something referred to as ACL: Access Control Lists or basically the capability to outline a persons' capability to do and see certain matters primarily based on attributes of their person record.
Is this helpful? Yes No
suggest an answer 0 Answer
6
4
Q. 104.What is Queues?
Queues in Laravel are used by developers to create smooth application cycle by stacking complex tasks as jobs and dispatching these heavy jobs only with user permission or when it doesn’t disrupt the user experience.
You can visits here for more details : www.laravel.com
Is this helpful? Yes No
suggest an answer 0 Answer
6 2
Q. 105.How to add multiple AND conditions in laravel query?
We can add multiple AND operator at in a single where() conditions as well as we can also add seprate where() for particular AND
condition.
Example
DB::table('client')->where('status', '=', 1)->where('name', '=', 'bestinterviewquestion.com')->get();
DB::table('client')->where(['status' => 1, 'name' => 'bestinterviewquestion.com'])->get();
Is this helpful?
Yes No
suggest an answer 0 Answer
6 3
Q. 106.How to get current action name in Laravel?
request()->route()->getActionMethod()
Is this helpful? Yes No
suggest an answer 0 Answer
10 1
Q. 107.What is Blade laravel?
Blade is very simple and powerful templating engine that is provided with Laravel. Laravel uses "Blade Template Engine".
Is this helpful? Yes No
suggest an answer 0 Answer
11 4
Q. 108.What is the use of event in laravel?
Events work as one great way in order to decouple several aspects of the
application as one single event is able to have various listeners and these listeners are independent of each other. Events in Laravel render a streamlined observer implementation that enables users to subscribe plus listen for several events that happen in the application. The classes of events are generally stored in the Events or app directory, on the other hand, listeners are kept in either app or Listeners.
Is this helpful? Yes No
suggest an answer 0 Answer
2 2
Q. 109.What is Pusher in Laravel?
Pusher is one hosted service with the help of which it has become immensely easy to add data of real-time along with
functionality to the web as well as mobile applications. Laravel Pusher sits like one real-time layer among the servers and the clients. It manages persistent connections with the clients. Plus it also offers libraries for integration into all of the major runtimes as well as frameworks. PHP, Python, Ruby, Java, Node as well as Go on the servers plus JavaScript, Java (Android) on the clients and Objective-C (iOS).
Is this helpful? Yes No
suggest an answer 0 Answer
3 1
Q. 110.What is broadcasting in laravel?
The Laravel 5.1 framework comprises functionality named broadcasting events. This new functionality makes it quite easy
to build real-time applications in PHP. And with this, an app will be able to publish the events to a number of real-time cloud-based PubSub solutions, such as Pusher, or Redis. Also, with this functionality called the broadcasting events which is built into the Laravel 5.1, it now became easier creating real-time applications for the PHP developers. This latest real-time capability unbars numerous possibilities that were available only to applications written for the other platforms such as Node.js.
Is this helpful? Yes No
suggest an answer 0 Answer
3 1
Q. 111.What do you mean by laravel echo?
The echo in Laravel is one tool
due to which it is easy for the users to bring in the Websocket's power to their Laravel applications. Echo streamlines some of the most common as well as the most complex aspects of making complicated WebSockets interactions. It comes in two parts, one- the series of amendments to the Event broadcasting system of Laravel and two- the new package of JavaScript.
Is this helpful? Yes No
suggest an answer 0 Answer
1 3
Q. 112.What is Horizon in Laravel 5?
Horizon in Laravel is the queue manager. It provides the user with full control of the queues, it renders the means for configuring how the jobs are processed and generates
analytics, plus performs various tasks related to queue from within one nice dashboard.
Is this helpful? Yes No
suggest an answer 0 Answer
3 2
Q. 113.What is Dusk in Laravel 5?
Dusk in Laravel renders one expressive and easy-to-use type of browser automation along with testing API. This By default does not demand to install the JDK or Selenium on the device. Instead, it uses one standalone installation of ChromeDriver. However, the users are free for utilizing any of the other compatible drivers of Selenium as per their wishes.
Is this helpful? Yes No
suggest an answer 0
Answer
2 3
Q. 114.What is mix in Laravel?
Mix in Laravel renders one fluent API to define Webpack creation steps for the application of Laravel that uses various common CSS as well as JavaScript preprocessors. With the help of one easy method chaining, the user is able to fluently define the asset pipeline.
Example:
mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css');
Is this helpful? Yes No
suggest an answer 0 Answer
4 1
Q. 115.What is Gulp in laravel?
Gulp in Laravel is simply one implementation that targets to make it comfortable for the
users who have recently acquainted themselves with the gulp in Laravel to be capable to manage their gulp file through adding the modules that work efficiently.
Is this helpful? Yes No
suggest an answer 0 Answer
3 1
Q. 116.What is fillable in laravel model?
It is an array which contains all those fields of table which can be create directly new record in your Database table.
Example
class User extends Model
{
protected $fillable = ['username', 'password', 'phone'];
}
Is this helpful? Yes No
suggest an answer 0 Answer
7 4
Q. 117.What is Guarded Attribute in a Model ?
It is the reverse of fillable. When a guarded specifies which fields are not mass assignable.
Related Article: PHP interview questions
Example
class User extends Model {
protected $guarded = ['user_type'];
}
Is this helpful? Yes No
suggest an answer 0 Answer
5 4
Q. 118.How to get user details when he is logged in by Auth?
Example
use IlluminateSupportFacadesAuth;
$userinfo = Auth::user();
print_r($userinfo );
Is this helpful? Yes No
suggest an answer 0 Answer
10 3
Q. 119.Is Laravel support caching? Explain
Yes, It supports caching like Memcached and Redis. By default, laravel is configured with file cache which is stores the serialized, cached objects in the files. Normally we can use Memcached or Redis for large projects.
Is this helpful? Yes No
suggest an answer 0 Answer
9 2
Q. 120.How to use traits in Laravel?
A Traits are
a technique for code reuse in single inheritance languages.
Example
I Created a Traits directory in my Http directory named BrandTrait.php
use AppHttpTraitsBrandTrait;
class YourController extends Controller {
use BrandTrait;
public function addProduct() {
//$brands =
Brand::all();
// $brands = $this->BrandTrait(); // this is wrong
$brands = $this->brandsAll();
}
}
Here is my BrandTrait.php
namespace AppHttpTraits;
use AppBrand;
trait BrandTrait {
public function brandsAll() {
// Get all the brands from the Brands model or table.
$brands = Brand::all();
return $brands;
}
}
Is this helpful? Yes No
suggest an answer 0 Answer
4 6
Q. 121.How to check Ajax request in Laravel?
You can use the following syntax to check ajax request in laravel.
if ($request->ajax()) {
// Now you can write your code here.
}
Is this helpful?
Yes No
suggest an answer 0 Answer
10 1
Q. 122.How to check if value is sent in request?
To check the email value is sent or not in request, you can use $request->has('email')
Example
if($request->has('email')) {
// email value is sent from request
} else {
// email value not sent from
request
}
Is this helpful? Yes No
suggest an answer 0 Answer
6 0
Q. 123.What are string and array helpers functions in laravel?
Laravel includes a number of global "helper" string and array functions. These are given below:-
Laravel Array Helper functions
Arr::add()
Arr::has()
Arr::last()
Arr::only()
Arr::pluck()
Arr::prepend() etc
Laravel String Helper
functions
Str::after()
Str::before()
Str::camel()
Str::contains()
Str::endsWith()
Str::containsAll() etc
Is this helpful? Yes No
suggest an answer 0 Answer
4 4
Q. 124.How to exclude a route with parameters from CSRF verification?
You can cut out a route from CSRF verification by using adding the route to $except property at VerifyCsrfToken middleware.
Example
protected $except = [
'admin/*/edit/*'
];
Is this helpful? Yes No
suggest an answer 0 Answer
6 3
Development History
Laravel was created by Taylor Otwell. Laravel's first beta version was released in June 2011. Laravel 2 was released in September 2011. Laravel 3 was released in February 2012. Laravel 4 was released in May 2013.
The majority of candidates are asked this information in laravel interview questions and answers. Laravel 6 was released on 3rd September 2019.
Key points about Laravel
Source code hosted on GitHub and licensed under MIT License.
Most Starred PHP Framework for custom software development on Github.
Its ability to use all of the new features of PHP sets it apart.
Friendly online community
Detailed documentation
Advantages of Laravel
It offers a rich set of functionalities.
Saves time.
The website built in Laravel is more scalable and secure.
Includes namespaces and interfaces that help to organize
resources.
Provides a clean API.
You can visit our youtube video and this is very helpful in cracking your Laravel interview https://www.youtube.com/watch?v=WmwCBDx0fOk
SOURCE: https://www.bestinterviewquestion.com/laravel-interview-questions
################################## LARAVEL ##################################################
Laravel interview questions
1) What is Laravel?
2) Explain Events in laravel ?
3) Explain validations in laravel?
4) How to install laravel via composer ?
5) List some features of laravel 6 ?
6) What is PHP artisan. List out some artisan commands ?
7) List some
default packages provided by Laravel Framework?
8) What are named routes in Laravel?
9) What is database migration. How to create migration via artisan ?
10) What are service providers in Laravel ?
11) Explain Laravel’s service container ?
12) What is composer ?
13) What is dependency injection in Laravel ?
14) What are Laravel Contract’s ?
15) Explain Facades in Laravel ?
16) What are Laravel eloquent?
17) How to enable query log in Laravel ?
18) What is reverse routing in Laravel?
19) How to turn off CRSF protection for specific route in Laravel?
20) What are traits in Laravel?
21) Does
Laravel support caching?
22) Explain Laravel’s Middleware?
23) What is Lumen?
24) Explain Bundles in Laravel?
25) How to use custom table in Laravel Modal ?
Last Updated: Jan 27, 2020,
Posted in Interview Questions,
35 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
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
Below are the list of Best Laravel interview questions and Answers
1) What is Laravel?
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.
VDO.AI
2) Explain Events in laravel ?
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.
3) Explain validations in laravel?
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',
]);
4) How to install laravel via composer ?
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
5) List some features of laravel 6 ?
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
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 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
7) List some default packages provided
by Laravel Framework?
Below are a list of some official/ default packages provided by Laravel
Cashier
Envoy
Passport
Scout
Socialite
Horizon
Telescope
8) What are named routes in Laravel?
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');
9) What is database migration. How to create migration via artisan ?
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
10) What are service providers in Laravel ?
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 IlluminateSupportServiceProvider 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
11) Explain Laravel’s service container ?
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.
12) What is composer ?
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 ?
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.
14) What are Laravel Contract’s ?
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
15) Explain Facades in Laravel ?
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 IlluminateSupportFacades namespace. You can easily access a facade like so:
use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('key');
});
16) What are Laravel eloquent?
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();
17) How to enable query log in Laravel ?
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();
18) What is reverse routing in Laravel?
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.
19) How to turn off CRSF protection for 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);
}
20) What are traits in Laravel?
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'
21) 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.
22) Explain Laravel’s Middleware?
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
23)
What is Lumen?
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
24) Explain Bundles in Laravel?
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
25) How to use custom table in Laravel Modal ?
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";
}
26) 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
27) 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.
28) 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
29) List some Aggregates methods provided by query builder in Laravel ?
count()
max()
min()
avg()
sum()
Also Read Laravel 5 interview questions 2019
30) How to check request is ajax or not ?
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";
}
31) Explain Inversion of Control, how to implement it.
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.
32) What is Singleton design pattern?
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.
33) Explain Dependency Injection and its types?
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
Click Here to Read More 100 Questions on Laravel 5 & 6
34) What is Laravel Vapor?
It is a serverless deployment platform that is powered by AWS.Laravel Vapor provides on-demand
auto-scaling with zero server maintenance.
35) What are pros and cons of using Laravel Framework?
Pros of using Laravel Framework
Laravel framework has in-built lightweight blade template engine to speed up compiling task and create layouts with dynamic content easily.
Hassles code reusability.
Eloquent ORM with PHP active record implementation
Built in command line tool “Artisan†for creating a code skeleton , database structure and build their migration
Cons of using laravel Framework
Development process requires you to work with standards and should have real understanding of programming
Laravel is new
framework and composer is not so strong in compare to npm (for node.js), ruby gems and python pip.
Development in laravel is not so fast in compare to ruby on rails.
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
Got a Questions? Share with us
Your Email
Question
Answer
Points to be remembered while appearing in Laravel Interviews :
Laravel is developed on the MVC (Model-View-Controller) design pattern.
Laravel comes with inbuilt features/ modules like authentication,
authorization, localization, models, views, sessions, paginations and routing
Laravel supports advanced concepts of PHP and OOPs like Dependency Injection, traits, Contracts, bundles, Namespaces, Facades
Laravel supports Multiple Databases like MySQL, PostgreSQL, SQLite, SQL Server.
Laravel allows developers to write a clean and modular code.
Laravel supports blade Template Engine
Laravel comes with Official Packages like Cashier, Envoy, Horizon, Passport, Scout, Socialite
Laravel can be used with various popular Javascript Frameworks Like AngularJs, VueJs, ReactJS.
Frequently Asked Laravel Developer Interview Questions.
What is Laravel
migration?
Migration in the Laravel is used to modify and share the structure of your database. It is paired with the schema builder in the Laravel to build the database for your application. It acts as a version control but for the Laravel database. There are two methods in the migration class, up and down. Up method is used to add tables, columns, to the database. The down method is used to reverse the operations of up. To create a migration, use make:migration command. To run the migration, use migrate command. It also offers a rollback feature.
Which version of Laravel you have used?
Answer the versions of Laravel you have worked on like Laravel 4, Laravel
5, Laravel 5.5, Laravel 6
What is socialite Laravel?
Laravel Socialite is an OAuth provider that is used to authenticate social media apps such as Facebook, Twitter, Google, and many more simply and seamlessly. It can be added to your Laravel web application using the dependency manager composer.
Why the composer is used in Laravel?
The composer in the Laravel is a dependency management tool that is used to install and manage libraries in your application. It does not install packages globally but on a per-application basis. Define the packages you want in the composer.json file and run the following command to install the packages in your
application.
How can you update Laravel?
To upgrade your Laravel framework to the latest version, open the composer.json file and change the version of the Laravel framework to the newest version. Then run the following command to update your Laravel framework.
composer update
How to use Laravel tinker?
Laravel Tinker is a REPL that allows the developer to interact with the Laravel application through the command line. To enter into the Tinker environment, enter the following command
php artisan tinker
Tinker allows you to run commands such as clear-compiled, down, env, inspire, migrate, optimize, and up by
default. To use more commands using Tinker, add the command to the command array that is present in the tinker.php configuration file.
How to use where relationship Laravel?
The where clause is a query builder that is used to verify something. Where has three arguments that it must require. The column name is the first argument with an operator as the second argument. The third argument is the value that the first operand must be evaluated using the operator.
Example
$users = DB::table('users')->where('salary', '=', 100)->get();
In the above example, the where clause is used to get the users who have the salary column that
is equal to 100.
What is the difference between Laravel find and where?
The where clause in the query is used to verify and retrieve values. It has three arguments. First is the column name argument. Second is the operator. The third is the values that need to be checked with the column name. It retrieves the first model that is matching the given query.
Example
$users = DB::table('students')->where('marks', '=', 100)->get();
The find method is used to retrieve a single model instance instead of a collection of models. It retrieves the model by its primary key.
$users = StudentModel::find(1);
How to hash
password in Laravel?
The Hash::make function is used to create a hash for the password.
Syntax:
Hash::make($password)
What are the Laravel guards?
The guard in Laravel is used to define the user authentication for each request. The Guards also provide a definition of user information storage and retrieval by the system. The session guard is a default guard in Laravel that is used to maintain the state using session storage and cookies. A web guard is used to store and retrieve session information. API guard is used to authenticate users and requests. These are some examples of default Laravel guard, and you can also create your own guard in
Laravel.
SOURCE: https://www.onlineinterviewquestions.com/laravel-interview-questions/
############################# LARAVEL #############################################
Laravel Interview Questions And Answers 2020
March 1, 2018 Coding Compiler 2 Comments Interview Questions, Laravel, Laravel Interview Questions, PHP Interview Questions
Laravel Interview Questions And Answers For Experienced 2020. Here Coding compiler sharing a list of 65 Real-Time Laravel interview questions for freshers and experienced. PHP Laravel questions were asked in various interviews conducted by the top MNC companies.
These technical interview questions on Laravel are prepared by industry expert PHP Laravel developers. This list will help you to crack your next Laravle job interview. All the best for your future and happy learning.
Laravel Interview Questions
What is the Laravel?
What is Laravel Horizon?
What is Laravel Dusk?
What is Laravel Echo?
How do you install Laravel?
What is Composer Tool?
What is Laravel service container?
What is Binding?
Explain Binding A Singleton?
Explain Binding Instances?
Explain Binding Primitives?
Explain Contextual Binding and how does it work?
What is Tagging?
Explain
Extending Bindings?
What is the make Method?
Must Read Laravel Books
Laravel Basic Level for Everybody
Laravel Basics: Creating Web Apps. ItÂ’s Simple.
Laravel 5.1 Beauty: Creating Beautiful Web Apps in Laravel 5.1
Laravel Design Patterns and Best Practices
Laravel: Up and Running: A Framework for Building Modern PHP Apps
Laravel Interview Questions And Answers
Laravel Interview Questions
Laravel is an Open source software
Laravel is a PHP web framework, created for the development of web applications.
Laravel follows Model–view–controller (MVC) architectural pattern.
Laravel created by Taylor
Otwell
Laravel Licence MIT License
Laravel has written in PHP 7
1) What is the Laravel?
A) Laravel is an open-source PHP web framework, created for the development of web applications following the model–view–controller (MVC) architectural pattern.
2) What is Laravel Horizon?
A) Laravel Horizon provides a beautiful dashboard and code-driven configuration for your Redis queues.
3) What is Laravel Dusk?
A) Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. You’ll love
it.
4) What is Laravel Echo?
A) Event broadcasting, evolved. Bring the power of WebSockets to your application without the complexity.
5) How do you install Laravel?
A) Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure we have Composer installed on your machine.
6) What is Composer Tool?
A) Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
7) What is Laravel service
container?
A) The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are “injected†into the class via the constructor or, in some cases, “setter†methods.
8) What is Binding?
A) Within a service provider, we always have access to the container via the $this->app property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with a Closure that returns an instance of the
class:
$this->app->bind(‘HelpSpotAPI’, function ($app) {
return new HelpSpotAPI($app->make(‘HttpClient’));
});
9) Explain Binding A Singleton?
A) The singleton method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container.
10) Explain Binding Instances?
A) You may also bind an existing object instance into the container using the instance method. The given instance will always be returned on subsequent
calls into the container:
$api = new HelpSpotAPI(new HttpClient);
$this->app->instance(‘HelpSpotAPI’, $api);
Top 65 Laravel Interview Questions
Laravel Interview Questions # 11) Explain Binding Primitives?
A) Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value such as an integer. You may easily use contextual binding to inject any value your class may
need:
$this->app->when(‘AppHttpControllersUserController’)
->needs(‘$variableName’)
->give($value);
Laravel Interview Questions # 12) Explain Contextual Binding and how does it work?
A) Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the IlluminateContractsFilesystemFilesystem contract. Laravel provides a simple, fluent interface for defining this behavior:
use IlluminateSupportFacadesStorage;
use
AppHttpControllersPhotoController;
use AppHttpControllersVideoController;
use IlluminateContractsFilesystemFilesystem;
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘local’);
});
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘s3’);
});
Laravel Interview Questions # 13) What is Tagging?
A) Occasionally, you may need to resolve all of a certain “category†of binding. For
example, perhaps you are building a report aggregator that receives an array of many different Report interface implementations. After registering the Report implementations, you can assign them a tag using the tag method:
$this->app->bind(‘SpeedReport’, function () {
//
});
$this->app->bind(‘MemoryReport’, function () {
//
});
$this->app->tag([‘SpeedReport’, ‘MemoryReport’], ‘reports’);
Once the services have been tagged, you may easily resolve them all via the tagged
method:
$this->app->bind(‘ReportAggregator’, function ($app) {
return new ReportAggregator($app->tagged(‘reports’));
});
Laravel Interview Questions # 14) Explain Extending Bindings?
A) The extend method allows the modification of resolved services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The extend method accepts a Closure, which should return the modified service, as its only argument:
$this->app->extend(Service::class, function($service) {
return new
DecoratedService($service);
});
Laravel Interview Questions # 15) What is the make Method?
A) You may use the make method to resolve a class instance out of the container. The make method accepts the name of the class or interface you wish to resolve:
$api = $this->app->make(‘HelpSpotAPI’);
Laravel Interview Questions # 16) What are service providers?
A) 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.
Laravel
Interview Questions # 17) What is Register Method?
A) 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.
Laravel Interview Questions # 18) Explain the bindings And singletons Properties?
A) If your service provider registers many simple bindings, you may wish to use the bindings and singletons properties instead of manually registering each container binding. When the service provider is loaded by the framework, it will automatically check for these properties and register
their bindings
Laravel Interview Questions # 19) What is the Boot Method?
A) if we need to register a view composer within our service provider? This should be done within the boot method. This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework.
Laravel Interview Questions # 20) Where do you regiser service providers?
A) All service providers are registered in the config/app.php configuration file. This file contains a providers array where you can list the class names of your service
providers.
PHP Laravel Interview Questions And Answers
Laravel Interview Questions # 21) How do you register service providers?
A) To register your provider, add it to the array:
‘providers’ => [
// Other Service Providers
AppProvidersComposerServiceProvider::class,
],
Laravel Interview Questions # 22) What are Facades?
A) Facades provide a “static†interface to classes that are available in the application’s service container.
Laravel Interview Questions # 23) Where Laravel’s facades are
defined?
A) All of Laravel’s facades are defined in the IlluminateSupportFacades namespace
Laravel Interview Questions # 24) What are the benefits of Facades?
A) Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laravel’s features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of PHP’s dynamic methods, they are easy to test.
Laravel Interview Questions # 25) Difference between Facades Vs. Dependency Injection?
A) One of the primary benefits of dependency
injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.
Typically, it would not be possible to mock or stub a truly static class method. However, since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance.
Laravel Interview Questions # 26) What is the difference between Facades Vs Helper Functions?
A) In addition to facades, Laravel includes a variety of “helperâ€
functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade.
Laravel Interview Questions # 27) What are Laravel’s Contracts?
A) Laravel’s Contracts are a set of interfaces that define the core services provided by the framework. For example, a IlluminateContractsQueueQueue contract defines the methods needed for queueing jobs, while the IlluminateContractsMailMailer contract defines the methods needed for sending e-mail.
Laravel Interview Questions # 28) What is the difference
between Contracts Vs Facades?
A) Laravel’s facades and helper functions provide a simple way of utilizing Laravel’s services without needing to type-hint and resolve contracts out of the service container. In most cases, each facade has an equivalent contract.
Unlike facades, which do not require you to require them in your class’ constructor, contracts allow you to define explicit dependencies for your classes. Some developers prefer to explicitly define their dependencies in this way and therefore prefer to use contracts, while other developers enjoy the convenience of facades.
Laravel Interview Questions # 29)
What is Routing in Laravel?
A) The most basic Laravel routes accept a URI and a Closure, providing a very simple and expressive method of defining routes:
Route::get(‘foo’, function () {
return ‘Hello World’;
});
Laravel Interview Questions # 30) Where do you locate Route files?
A) All Laravel routes are defined in your route files, which are located in the routes directory.
Laravel PHP Developer Interview Questions
Laravel Interview Questions # 31) What are the available Router Methods?
A) The router allows
you to register routes that respond to any HTTP verb:
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Laravel Interview Questions # 32) What is CSRF Protection?
A) aravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.
Laravel Interview Questions # 33) What is CSRF
Protection Token?
A) Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.
<form method=â€POST†action=â€/profileâ€>
@csrf
…
</form>
Laravel Interview Questions # 34) What is Redirect Routes?
A) If you are defining a route that redirects to another URI, you may use the Route::redirect method.
Route::redirect(‘/here’, ‘/there’, 301);
Laravel Interview Questions # 35) What is View
Routes?
A) If your route only needs to return a view, you may use the Route:: view method. The view method accepts a URI as its first argument and a view name as its second argument. In addition, you may provide an array of data to pass to the view as an optional third argument.
Route::view(‘/welcome’, ‘welcome’);
Route::view(‘/welcome’, ‘welcome’, [‘name’ => ‘Taylor’]);
Laravel Interview Questions # 36) What is Named Routes?
A) Named routes allow the convenient generation of URLs or redirects for specific routes. You
may specify a name for a route by chaining the name method onto the route definition:
Route::get(‘user/profile’, function () {
//
})->name(‘profile’);
Laravel Interview Questions # 37) What are Route Groups?
A) Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route.
38) What is Route Model Binding?
A) When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID.
Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes.
Laravel Interview Questions # 39) What is Rate Limiting?
A) Laravel includes a middleware to rate limit access to routes within your application. To get started, assign the throttle middleware to a route or a group of routes.
The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes. For example, let’s specify that an authenticated user may access the following group of routes 60 times per
minute:
Route::middleware(‘auth:api’, ‘throttle:60,1’)->group(function () {
Route::get(‘/user’, function () {
//
});
});
Laravel Interview Questions # 40) What is Middleware?
A) Middleware provide a convenient mechanism for filtering HTTP requests entering your application.
Advanced Laravel Interview Questions And Answers
41) How do you define Middleware?
A) To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware CheckAge
This command will place a
new CheckAge class within your app/Http/Middleware directory.
42) What are Middleware Groups?
A) Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroups property of your HTTP kernel.
43) What is X-CSRF-TOKEN?
A) In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:
<meta name=â€csrf-token†content=â€{{ csrf_token()
}}â€>
44) What is X-XSRF-TOKEN?
A) Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.
45) What is Response in Laravel?
A) All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP
response:
Route::get(‘/’, function () {
return ‘Hello World’;
});
46) What are Redirect responses?
A) Redirect responses are instances of the IlluminateHttpRedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
Route::get(‘dashboard’, function () {
return redirect(‘home/dashboard’);
});
47) What is Response Macros?
A) If you would like to
define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade.
48) What is View?
A) Views contain the HTML served by your application and separate your controller / application logic from your presentation logic. Views are stored in the resources/views directory. A simple view might look something like this:
<!– View stored in resources/views/greeting.blade.php –>
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
48) What are View
Composers?
A) View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.
49) What are View Creators?
A) View creators are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the creator method:
View::creator(‘profile’,
‘AppHttpViewCreatorsProfileCreator’);
50) How do you generate URLs?
A) Laravel provides several helpers to assist you in generating URLs for your application. Of course, these are mainly helpful when building links in your templates and API responses, or when generating redirect responses to another part of your application.
Laravel Interview Questions For 2, 3, 4, 5 Years Experience
51) What is url helper?
A) The url helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current
request:
$post = AppPost::find(1);
echo url(“/posts/{$post->id}â€);
// http://example.com/posts/1
52) Exceptions are handled by which class?
A) All exceptions in Laravel are handled by the AppExceptionsHandler class. This class contains two methods: report and render.
53) What is report method?
A) The report method is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however
you wish.
54) What is the render method?
A) The render methos is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you.
55) What are HTTP Exceptions?
A) Some exceptions describe HTTP error codes from the server. For example, this may be a “page not found†error (404), an “unauthorized error†(401) or even a developer generated 500 error.
56) What is Monolog library?
A) Laravel utilizes the Monolog library, which
provides support for a variety of powerful log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix and match them to customize your application’s log handling.
57) What is stack channel?
A) By default, Laravel will use the stack channel when logging messages. The stack channel is used to aggregate multiple log channels into a single channel.
58) What are Blade Templates?
A) Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your
views.
59) Where is the authentication configuration file is located in Laravel?
A) The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services.
60) What is fluent query builder in Laravel?
A) Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.
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.
61) What is Eloquent ORM in Laravel?
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. 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.
62) Laravle supports which databases?
A) Laravel makes interacting with databases extremely simple across a variety of database backends using
either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four databases:
MySQL
PostgreSQL
SQLite
SQL Server
63) Where do you locate database configuration file?
A) The database configuration for your application is located at config/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default.
64) What is Redis?
A) Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and
sorted sets.
65) Can you explain about Serialization?
A) When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes conv
35) What are the requirements for Laravel 5.8?
PHP Version>=7.1.3
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension
36) In which directory controllers are kept in Laravel?
Controllers are kept in app/http/Controllers directory.
37) What is the use of PHP compact function?
PHP compact function receives each key and tries to search a variable with that same name. If a variable is found, then it builds an associate array.
38) What are the major differences between Laravel 4 and
Laravel 5.x?
The major differences between Laravel 4 and Laravel 5.x are given below:
The old app/models directory is entirely removed.
Controllers, middleware, and requests (a new class in Laravel 5.0) are now combined under the app/Http directory.
A new app/Providers directory changes the app/start files from previous versions of Laravel of 4.x.
Application language files and views are moved to the resources directory.
All major Laravel components include interfaces that are located in the illuminate/contracts repository.
Laravel 5.x now supports HTTP middleware. The included authentication and CSRF "filters" are converted to
middleware.
One can now type-hint dependencies on controller methods.
User authentication, registration, and password reset controllers are now combined out of the box, including simple related views which are located at resources/views/auth.
One can now define events as objects instead of simply using strings.
Laravel 5 also allows us to represent our queued jobs as simple command objects in addition to the queue job format, which was supported in Laravel 4. These commands are available inside the app/Commands display.
39) Explain some benefits of Laravel over other PHP frameworks.
There are few benefits of Laravel which can be considered over other PHP
frameworks:
In Laravel, Setup and customization process is fast and easy as compared to others.
Laravel supports multiple file systems.
It has pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel Passport, Laravel elixir, and Laravel Scout, etc.
It consists of in-built Authentication System.
It supports Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
"Artisan" command-line tool for creating a database structure, code skeleton, and build their migration.
40) Which types of relationships are available in Laravel Eloquent?
Below are the types of relationships that Laravel Eloquent ORM
supports:
One to One
One to Many
One to Many (Inverse)
Many to Many
Has Many Through
Polymorphic Relations
Many To Many Polymorphic Relations
41) What do you understand by ORM?
ORM stands for Object-Relational Mapping. It is a programming technique which is used to convert data between incompatible type systems in object-oriented programming languages.
42) How can we implement a package in Laravel?
We can implement a package in Laravel by:
Creating a package folder and name it.
Creating Composer.json file for the package.
Loading package through main composer.json and
PSR-4.
Creating a Service Provider.
Creating a Controller for the package.
Creating a Routes.php file.
43) What do you know about Traits in Laravel?
PHP Traits is a group of methods which can be included within another class. A Trait cannot be instantiated by itself like an abstract class. Traits are generated to reduce the limitations of single inheritance in PHP. It allows a developer to reuse sets of methods freely in various independent classes living in different class hierarchies.
Example
trait Sharable {
public function share($item)
{
return 'share this item';
}
}
We can then include this Trait within other classes like:
class Post {
use Sharable;
}
class Comment {
use Sharable;
}
Now, if we want to create new objects out of these classes, we 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'
44) How can someone change the default database type in Laravel?
Laravel is configured
to use MySQL by default.
To change its default database type, edit the file config/database.php:
Search for 'default' =>env('DB_CONNECTION', 'mysql')
Change it to whatever required like 'default' =>env('DB_CONNECTION', 'sqlite')
By using it, MySQL changes to SQLite.
45) How can we use maintenance mode in Laravel 5?
When an application is in maintenance mode, a custom view is displayed for all requests into the application. It makes it easy to "disable" application while it is updating or performing maintenance. A maintenance mode check is added in the default middleware stack for our application. When an
application is in maintenance mode, a MaintenanceModeException will be thrown with a status code of 503.
We can enable or disable maintenance mode in Laravel 5, simply by executing the below command:
// Enable maintenance mode
php artisan down
// Disable maintenance mode
php artisan up
46) How can we create a record in Laravel using eloquent?
We need to create a new model instance if we want to create a new record in the database using Laravel eloquent. Then we are required to set attributes on the model and call the save() method.
Example
public
functionsaveProduct(Request $request )
$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();
47) How can we check the logged-in user info in Laravel?
User() function is used to get the logged-in user
Example
if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}
48) How will you describe Fillable Attribute in a Laravel model?
In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using
mass-assignment.
Mass assignment refers to sending an array to the model to directly create a new record in Database.
Code Source
class User extends Model {
protected $fillable = ['name', 'email', 'mobile'];
// All fields inside $fillable array can be mass-assigned
}
49) How will you explain Guarded Attribute in a Laravel model?
The guarded attribute is the opposite of fillable attributes.
In Laravel, fillable attributes are used to specify those fields which are to be mass assigned. Guarded attributes are used to specify those fields which are not mass
assignable.
Code Source
class User extends Model {
protected $guarded = ['role'];
// All fields inside the $guarded array are not mass-assignable
}
If we want to block all the fields from being mass-assigned, we can use:
protected $guarded = ['*'];
$fillable serves as a "white list" whereas $guarded functions serves like a "black list". One should use either $fillable or $guarded.
50) What do you know about Closures in Laravel?
In Laravel, a Closure is an anonymous method which can be used as a callback function. It can also be used as a
parameter in a function. It is possible to pass parameters into a Closure. It can be done by changing the Closure function call in the handle() method to provide parameters to it. A Closure can access the variables outside the scope of the variable.
Example
function handle(Closure $closure) {
$closure();
}
handle(function(){
echo 'Interview Question';
});
It is started by adding a Closure parameter to the handle() method. We can call the handle() method and pass a service as a parameter.
By using $closure(); in the handle() method, we tell
Laravel to execute the given Closure which will then display the 'Interview Question.'
Interview Tips Job/HR Interview Questions
JavaScript Interview Questions jQuery Interview Questions
Java Basics Interview Questions Java OOPs Interview Questions
Servlet Interview Questions JSP Interview Questions
Spring Interview Questions Hibernate Interview Questions
PL/SQL Interview Questions SQL Interview Questions
Oracle Interview Questions Android Interview Questions
SQL Server Interview Questions MySQL Interview Questions
SOURCE:
https://www.javatpoint.com/laravel-interview-questions
############################## LARAVEL ############################
Laravel is a PHP web framework. It is used in developing applications for web, mobile. Laravel is a open source SDK similar to IOS. Applications are developed based on MVC structure i.e. model view and controller. It has simple and expressive syntax and easy to develop the apps using Laravel. Laravel 5.6 is the latest release in 2018 that had many new features. Candidates should have knowledge on IOS concepts and developing mobile apps. There are number of positions available across all the locations. Wisdomjobs focus on providing interview
questions and answers to help you in clearing the interview with ease. Laravel interview questions are useful to attend job interviews and get shortlisted for job position. Check out interview questions page to get more information.
Laravel Interview Questions And Answers PrevLaravel Interview Questions
Laravel Tutorial
Laravel Jobs
All Interview Questions
Question 1. Does Laravel Support Caching?
Answer :
Yes, Its provides.
Question 2. How To Use Delete Statement In Laravel?
Answer :
DB::delete('delete
from users where id = ?', [1015]);
Python Interview Questions
Question 3. How To Use Update Statement In Laravel?
Answer :
DB::update('update users set city_id = 10 where id = ?', [1015]);
Question 4. How To Use Insert Statement In Laravel?
Answer :
DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]);
Python Tutorial
Question 5. How To Use Select Query In Laravel?
Answer :
$users = DB::select('select * from users where city_id = ?',
10);
if(!empty($users)){
foreach($users as $user){
}
}
PHP Interview Questions
Question 6. How To Enable The Query Logging?
Answer :
DB::connection()->enableQueryLog();
Question 7. How To Set Database Connection In Laravel?
Answer :
Database configuration file path is : config/database.php
Following are sample of database file :
'mysql' => [
'read' => [
'host' =>
'localhost',
],
'write' => [
'host' => 'localhost'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
PHP Tutorial Zend Interview Questions
Question 8. What Are Bundles,reverse Routing And The Ioc Container ?
Answer
:
Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.
Question 9. Compare Laravel With Codeigniter?
Answer :
Laravel :
Laravel is a framework with expressive, elegant syntax
Development is enjoyable, creative experience
Laravel is built for latest version of
PHP
It is more object oriented compared to CodeIgniter
Laravel community is still small, but it is growing very fast.
Codeigniter :
CodeIgniter is a powerful PHP framework
Simple and elegant toolkit to create full-featured web applications.
Codeigniter is an older more mature framework
It is less object oriented compared to Laravel.
Codeigniter community is large.
AJAX Interview Questions
Question 10. What Are The Feature Of Laravel 5.0?
Answer :
Method injection
Contracts
Route caching
Events object
Multiple file
system
Authentication Scaffolding
dotenv – Environment Detection
Laravel Scheduler
Zend Tutorial
Question 11. Explain About Laravel Project?
Answer :
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.
MySQL Interview Questions
Question 12. What Are Advantages Of Laravel?
Answer :
Easy and consistent syntax
Set-up process is easy
customization process is easy
code is always
regimented with Laravel
Python Interview Questions
Question 13. What Is Laravel?
Answer :
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites.
Laravel helps you create applications using simple, expressive syntax.
AJAX Tutorial
Question 14. What Is System Requirement For Installation Of Laravel 5.2 (latest Version)?
Answer :
PHP >= 5.5.9
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
Question 15. How To
Install Laravel?
Answer :
We can install the Laravel in following ways.
Laravel Installer
Composer Create-Project
Drupal Interview Questions
Question 16. Is Laravel An Open Source?
Answer :
Yes, Download the framework and use as per your requirement
MySQL Tutorial
Question 17. What Is Offical Website Url Of Laravel?
Answer :
laravel.com.
WordPress Interview Questions
Question 18. In Which Language It Was Written?
Answer
:
PHP.
PHP Interview Questions
Question 19. What Is Current Stable Version Of Laravel?
Answer :
Version 5.2.36 dated June 6, 2016
Drupal Tutorial
Question 20. When Laravel Was Launched?
Answer :
June 2011
Java Abstraction Interview Questions
Question 21. What Developed The Laravel?
Answer :
Taylor Otwell.
Question 22. What Are System Requirement For Laravel 5.0?
Answer
:
Following are system requirements:
PHP >= 5.4, PHP < 7
Mcrypt PHP Extension
OpenSSL PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
WordPress Tutorial
Laravel Related Tutorials
Python Tutorial PHP Tutorial
Zend Tutorial AJAX Tutorial
MySQL Tutorial Drupal Tutorial
WordPress Tutorial Javascript Advanced Tutorial
CodeIgniter Tutorial Phonegap Tutorial
wxPython Tutorial PHP7 Tutorial
Laravel Related Interview Questions
Python Interview Questions PHP Interview Questions
Zend Interview Questions AJAX Interview
Questions
MySQL Interview Questions Drupal Interview Questions
WordPress Interview Questions Java Abstraction Interview Questions
Javascript Advanced Interview Questions CodeIgniter Interview Questions
Phonegap Interview Questions wxPython Interview Questions
PHP7 Interview Questions
Laravel Related Practice Tests
Python Practice Tests PHP Practice Tests
Zend Practice Tests AJAX Practice Tests
MySQL Practice Tests Drupal Practice Tests
WordPress Practice Tests CodeIgniter Practice Tests
Phonegap Practice Tests
######################## LARAVEL #######################################
Best Laravel
Interview Questions and Answers
1. What is Laravel?
An open source free "PHP framework" based on 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.
2. List some official packages provided by Laravel?
Below are some official packages provided by Laravel
Cashier :Laravel Cashier provides an expressive, fluent interface to Stripe's and Braintree's subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier
can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.Read More
Envoy :Laravel Envoy provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems.
Read More
Passport :Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by
Alex Bilbie.
Read More
Scout :Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.Read More
Socialite :Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket. It handles almost all of the boilerplate social authentication code you are dreading writing.Read More
3. What is the latest version of Laravel?
Laravel 5.8.29 is the latest version of Laravel. Here are steps to install and configure Laravel
5.8.29
4. What is Lumen?
Lumen is PHP micro framework that built on Laravel's top components. It is created by Taylor Otwell.
It is the perfect option for building Laravel based micro-services and fast REST API's. It's one of the fastest micro-frameworks available.
5. List out some benefits of Laravel over other Php frameworks?
Top benifits of laravel framework
Setup and customization process is easy and fast as compared to others.
Inbuilt Authentication System.
Supports multiple file systems
Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel
Scout.
Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
Built in command line tool "Artisan" for creating a code skeleton ,database structure and build their migration.
6. List out some latest features of Laravel Framework
Inbuilt CRSF (cross-site request forgery ) Protection.
Laravel provided an easy way to protect your website from cross-site request forgery (CSRF) attacks.
Cross-site request forgeries are malicious attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.
Inbuilt paginations Laravel provides an easy
approach to implement paginations in your application.Laravel's paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database.
Reverse Routing
In Laravel reverse routing is generating URL's based on route declarations.Reverse routing makes your application so much more flexible.
Query builder:
Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.
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. read more
Route caching
Database Migration
IOC (Inverse of Control) Container Or service container.
7. How can you display HTML with Blade in Laravel?
To display html in laravel you can use below synatax.
{!! $your_var !!}
8. What is composer?
Composer is PHP dependency manager used for installing dependencies of PHP applications.It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
It provides us a nice way to reuse any kind of code. Rather than all of us
reinventing the wheel over and over, we can instead download popular packages.
9. How to install Laravel via composer?
To install Laravel with composer run below command on your terminal.
composer create-project Laravel/Laravel your-project-name version
10. 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 are the list of some artisian 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
11. How to check current installed version of Laravel?
Use php artisan –version command to check current installed version of Laravel Framework
Usage:
php artisan --version
12. List some Aggregates methods provided by query builder in Laravel?
Aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list.
Below is list of some Aggregates
methods provided by Laravel query builder.
count()
Usage:$products = DB::table(‘products’)->count();
max()
Usage:$price = DB::table(‘orders’)->max(‘price’);
min()
Usage:$price = DB::table(‘orders’)->min(‘price’);
avg()
Usage:$price = DB::table(‘orders’)->avg(‘price’);
sum()
Usage: $price = DB::table(‘orders’)->sum(‘price’);
13. Explain Events in Laravel?
Laravel events:
An event is an incident or occurrence detected and handled by the program.Laravel event
provides a simple observer implementation, that allow us to subscribe and listen for events in our application.An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allows us to subscribe and listen for events in our application.
Below are some events examples in Laravel:-
A new user has registered
A new comment is posted
User login/logout
New product is added.
14. How to turn off CRSF protection for a route in Laravel?
To turn off or diasble CRSF protection for specific routes in Laravel open "app/Http/Middleware/VerifyCsrfToken.php" file and
add following code in it
//add this in your class
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);}
15. What happens when you type "php artisan" in the command line?
When you type "PHP artisan" it lists of a few dozen different command
options.
16. Which template engine Laravel use?
Laravel uses Blade Templating Engine.
Blade is the simple, yet powerful templating engine provided with 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.
17. 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 and search for ‘default’ => ‘mysql’ and change it to whatever you want (like ‘default’ => ‘sqlite’).
18. Explain Migrations in Laravel? How can you generate migration .
Laravel Migrations are like version control for your database, allowing a 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.
Steps to Generate Migrations in Laravel
To create a
migration, use the make:migration Artisan command
When you create a migration file, Laravel stores it in /database/migrations directory.
Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.
Open the command prompt or terminal depending on your operating system.
19. What are service providers in laravel?
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.
Service provider basically registers event listeners, middleware,
routes to Laravel’s service container.
All service providers need to be registered in providers array of app/config.php file.
20. How do you register a Service Provider?
To register a service provider follow below steps:
Open to config/app.php
Find ‘providers’ array of the various ServiceProviders.
Add namespace ‘IluminateAbcABCServiceProvider:: class,’ to the end of the array.
21. What are Implicit Controllers?
Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route: controller
method.
Usage :
Route::controller('base URI','<class-name-of-the-controller>');</class-name-of-the-controller>
22. What does "composer dump-autoload" do?
Whenever we run "composer dump-autoload"
Composer re-reads the composer.json file to build up the list of files to autoload.
23. Explain Laravel service container?
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.
24. How can you get users IP address in Laravel?
You can use request’s class ip() method to get IP address of user in Laravel.
Usage:public function getUserIp(Request $request){
// Getting ip address of remote user
return $user_ip_address=$request->ip();
}
25. What are Laravel Contracts?
Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravel framework.
26. How to enable query log in
Laravel?
Use the enableQueryLog method: Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get an array of the executed queries by using the getQueryLog method:
$queries = DB::getQueryLog();
27. What are Laravel Facades?
Laravel Facades provides a static like 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 provides 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 IlluminateSupportFacades namespace. You can easily access a Facade like so:
use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('key');
});
28. How to use custom table in Laravel Model?
We can use custom table in Laravel by overriding protected $table property of Eloquent. Below is sample uses:
class User extends Eloquent{
protected $table="my_custom_table";
}
29. How can you define Fillable Attribute
in a Laravel Model?
You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses
Class User extends Eloquent{
protected $fillable =array('id','first_name','last_name','age');
}
30. What is the purpose of the Eloquent cursor() method in Laravel?
The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage.
Example Usageforeach (Product::where('name', 'bar')->cursor() as $flight) {
//do
some stuff
}
31. What are Closures in Laravel?
Closures are an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.
32. What is Kept in vendor directory of Laravel?
Any packages that are pulled from composer is kept in vendor directory of Laravel.
33. What does PHP compact function do?
Laravel's compact() function takes each key and tries to find a variable with that same name.If the variable is found, them it builds an associative array.
34. In which directory controllers are
located in Laravel?
We kept all controllers in App/Http/Controllers directory
35. Define ORM?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
36. How to create a record in Laravel using eloquent?
To create a new record in the database using Laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method:
Here is sample Usage.public function saveProduct(Request $request ){
$product = new product;
$product->name =
$request->name;
$product->description = $request->name;
$product->save();
}
37. How to get Logged in user info in Laravel?
Auth::User() function is used to get Logged in user info in Laravel.
Usage:-
if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}
38. 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.
39. What are named routes in Laravel?
Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Url’s 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');
40. What are traits in Laravel?
Laravel Traits are simply a group of methods that you want include within another class. A Trait, like an abstract classes 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.
Laravel Triats Exampletrait 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'
41. How to create migration via artisan?
Use below commands to create migration data via artisan.
php artisan make:migration create_users_table
42. Explain validations in Laravel?
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.
43. Explain Laravel Eloquent?
Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP MAPPING). It provides a beautiful, simple ActiveRecord implementation to work with your database. In Eloquent each database table has the corresponding MODEL that is used to interact with table and perform a database related operation on the table.
Sample Model Class in Laravel.namespace App;
use IlluminateDatabaseEloquentModel;
class Users extends Model
{
}
44. Can laravel be hacked?
Answers to this question is NO.Laravel
application’s are 100% secure (depends what you mean by "secure" as well), in terms of things you can do to prevent unwanted data/changes done without the user knowing.
Larevl have inbuilt CSRF security, input validations and encrypted session/cookies etc. Also, Laravel uses a high encryption level for securing Passwords.
With every update, there’s the possibility of new holes but you can keep up to date with Symfony changes and security issues on their site.
45. Does Laravel support PHP 7?
Yes,Laravel supports php 7
46. Define Active Record Implementation. How to use it
Laravel?
Active Record Implementation is an architectural pattern found in software engineering that stores in-memory object data in relational databases. Active Record facilitates the creation and use of business objects whose data is required to persistent in the database. Laravel implements Active Records by Eloquent ORM. Below is sample usage of Active Records Implementation is Laravel.
$product = new Product;
$product->title = 'Iphone 6s';
$product->save();
Active Record style ORMs map an object to a database row. In the above example, we would be mapping the Product object to a row in the products
table of database.
47. List types of relationships supported by Laravel?
Laravel support 7 types of table relationships, they are
One To One
One To Many
One To Many (Inverse)
Many To Many
Has Many Through
Polymorphic Relations
Many To Many Polymorphic Relations
48. Explain Laravel Query Builder?
Laravel's database query builder provides a suitable, easy interface to creating and organization database queries. It can be used to achieve most database operations in our application and works on all supported database systems. The Laravel query planner uses PDO restriction necessary to keep our application
against SQL injection attacks.
49. What is Laravel Elixir?
Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports common CSS and JavaScript preprocessors like Sass and Webpack. Using method chaining, Elixir allows you to fluently define your asset pipeline.
50. How to enable maintenance mode in Laravel 5?
You can enable maintenance mode in Laravel 5, simply by executing below command.
//To enable maintenance mode
php artisan down
//To disable maintenance mode
php artisan up
51. List out Databases Laravel
supports?
Currently Laravel supports four major databases, they are :-
MySQL
Postgres
SQLite
SQL Server
52. How to get current environment in Laravel 5?
You may access the current application environment via the environment method.
$environment = App::environment();
dd($environment);
53. What is the purpose of using dd() function iin Laravel?
Laravel's dd() is a helper function, which will dump a variable's contents to the browser and halt further script execution.
54. What is Method Spoofing in Laravel?
As HTML forms does not supports PUT, PATCH or DELETE request. So, when
defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
To generate the hidden input field _method, you may also use the method_field helper function:
<?php echo method_field('PUT'); ?>
In Blade template you can write it as below
{{
method_field('PUT') }}
55. How to assign multiple middleware to Laravel route ?
You can assign multiple middleware to Laravel route by using middleware method.
Example:// Assign multiple multiple middleware to Laravel to specific route
Route::get('/', function () {
//
})->middleware('firstMiddleware', 'secondMiddleware');
// Assign multiple multiple middleware to Laravel to route groups
Route::group(['middleware' => ['firstMiddleware','secondMiddleware']], function () {
//
});
This post is submitted by one of our members. You may
submit a new post here.
Laravel questions and answers
Related Tricks
What is reverse routing in Laravel?
Installing soap module on PHP 7 ubuntu
Generating application key in Lumen
How to get user details by id or email in Laravel?
Sending data to view using redirect in Laravel?
Installing Laravelcollective/html package in laravel 5.5
How to Clear cache in Laravel?
What does "composer dump-autoload" do?
Rollback all migrations in Laravel
Active Record Implementation in Laravel?
Call to a member function connection() on null Laravel Lumen
How to check current installed version of Laravel
?
SOURCE: https://www.wisdomjobs.com/e-university/laravel-interview-questions.html
################# LARAVEL ########################
How to assign multiple middleware to Laravel route ?
How to resolve phpunit/phpunit 5.7.8 requires ext-dom * error while installing Laravel 5
Reading writing and deleting a File from disk or filesystem in Laravel 5
How to resolve MassAssignment Exception _token error in Laravel 5?
How to enable query log in Laravel?
How to get records between two date in Laravel using eloquent
What are named routes in Laravel?
How to run Laravel Development server?
How to
protect your .env file from public access in Laravel?
Laravel Http to https
Paginating records in Laravel
Cross-Origin Request Blocked error in Laravel 5
Call to undefined function csrf_field()
Create image from base64 string laravel
Difference between –prefer-dist and –prefer-source options in composer
How to secure .env file in Laravel
Non-static method should not be called statically Laravel
Function to get excerpt from Laravel string
Laravel: Sanitize Request Input by using Sanitizing Middleware
Method spoofing in Laravel
Changing storage path permission in Laravel
What is the purpose of the
Eloquent cursor() method in Laravel
How to use custom table in Laravel Model?
Using Session in Laravel
Class ‘DB’ not found in Lumen
Ajax code to delete file in laravel
DB prefix in Lumen Framework.
Installing specific version of Laravel with Composer
Step by step guide to display wordpress posts in Laravel 5
findorFail method in Laravel
Laravel get ip address
Image Manipulation in Laravel 5
Using multiple Where clause Query in Laravel.
Laravel migration change column type
What new in Laravel 6
PHP Artisan
PHP artisan migrate command
Run raw query in Laravel.
php artisan serve
not working
php artisan serve stop
Laravel phone number validation
Laravel get server ip
Where not in Laravel
How to create zip files in Laravel?
Creating zip of multiple files and download in Laravel.
Laravel get data from database by id.
List some official packages provided by Laravel.
Service providers in Laravel
How to enable maintenance mode in Laravel 5?
Getting Random rows in Laravel Eloquent.
IN query in Laravel Eloquent
Disabling timestamps in Laravel Eloquent
Explain migrations in Laravel? How can you generate migration.
Read and Write Cookie in Laravel 5
Adding Multiple Order By clause
in Laravel
Disabling error handler in laravel
What happens when AUTO_INCREMENT reaches the maximum value?
What is an Initialization function in PHP?
clear-compiled Command in Laravel
PHP artisan optimize command
Laravel delete migration
sqlstate hy000 error 2002 laravel
How to get all records in Laravel?
SOURCE: http://www.laravelinterviewquestions.com/blog/laravel-interview-questions-nja/
############################### LARAVEL ######################################
####################################### LARAVEL ######################################
1. What is Laravel?
Laravel is free
open source “PHP framework†based on 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.
2. What are pros and cons of using Laravel Framework?
Pros of using laravel Framework
Laravel framework has in-built lightweight blade template engine to speed up compiling tasks and create layouts with dynamic content easily.
Hassles code reusability.
Eloquent ORM with PHP active record implementation
Built-in command-line tool “Artisan†for creating a code skeleton ,database structure and build their migration
Cons
of using laravel Framework
The development process requires you to work with standards and should have a real understanding of programming
Laravel is a new framework and the composer is not so strong in compare to npm (for node.js), ruby gems and python pip.
Development in laravel is not so fast in compare to ruby on rails.
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
Laravel Interview Questions
3. Explain Events in Laravel ?
An event is an action or occurrence
recognized by a program that may be handled by the program or code. Laravel events provide 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 the app/Listeners of your application.
4. Explain validations in laravel?
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 ValidatesRequeststrait 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.
5. List some Aggregates methods provided by query builder in Laravel?
An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list.
Below is list of some Aggregates methods provided by Laravel query builder.
count()
Usage:$products = DB::table(‘products’)->count();
max()
Usage:$price =
DB::table(‘orders’)->max(‘price’);
min()
Usage:$price = DB::table(‘orders’)->min(‘price’);
avg()
Usage:$price = DB::table(‘orders’)->avg(‘price’);
sum()
Usage: $price = DB::table(‘orders’)->sum(‘price’);
6. What is the service container in laravel?
Service Container is a powerful tool that is used to manage class dependencies and perform dependency injection. It is also known as the IoC container. It offers several benefits to users such as.
Advantages of Service