Laravel interview questions and answers ๐
Laravel General Interview Questions
How can you generate URLs?
โLaravel has helpers to generate URLs. This is helpful when you build link in your templates and API response.
List out common artisan commands used in Laravel
โ- PHP artisan down;
- PHP artisan up;
- PHP artisan make:controller;
- PHP artisan make:model;
- PHP artisan make:migration;
- PHP artisan make:middleware;
In which folder robot.txt is placed?
โRobot.txt file is placed in Public directory.
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.
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.
List available types of relationships in Laravel Eloquent.
โTypes of relationship in Laravel Eloquent are:
- One To One
- One To Many
- Many To Many
- Has Many Through, and
- Polymorphic Relations.
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.
What is X-XSRF-TOKEN?
โ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.
What is benefits of using "Blade" Template in Laravel?
โUnlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.
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.
What are common HTTP error codes?
โ- Error 404 โ Displays when Page is not found.
- Error- 401 โ Displays when an error is not authorized
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.
How to get current environment in Laravel?
โ$environment = App::environment();
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.
Define Lumen.
โLumen is a micro-framework. It is a smaller, and faster, version of a building Laravel based services, and REST API's.
Which file is used to create a connection with the database?
โTo create a connection with the database, you can use .env file.
In which directory controllers are kept in Laravel?
โControllers are kept in app/http/Controllers directory.
What does ORM stand for?
โORM stands for Object Relational Mapping
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.
What are the advantages of using 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.
What is Laravel Forge?
โLaravel Forge is a tool that helps in organising and designing a web application. Although the manufacturers of the Laravel framework developed it, it can automate the deployment of every web application that works on a PHP server.
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:
- Username
- Password
Where will you define Laravel's Facades?
โAll facades of Laravel are defined in Illuminate\Support\Facades namespace.
Name databases supported by Laravel.
โ- PostgreSQL
- SQL Server
- SQLite
- MySQL
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.
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.
What are the difference between insert() and insertGetId() in laravel?
โ- 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.
- Inserts(): This method is used for insert records into the database table. No need the "id" should be autoincremented or not in the table.
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.
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.
What is a raw expression in laravel?
โRaw Expressions allow you to tell the query builder that you want to use what you entered and not get processed or manipulate before running the query against the database.
State the difference between authentication and authorization.
โAuthentication means confirming user identities through credentials, while authorization refers to gathering access to the system.
Name some Inbuilt Authentication Controllers of Laravel.
โ- RegisterController
- LoginController
- ResetPasswordController
- ForgetPasswordController
Explain active record concept in Laravel.
โIn active record, class map to your database table. It helps you to deal with CRUD operation.
In which language Laravel is written ?
โLaravel is written in PHP.
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.
How can we check the logged-in user info in Laravel?
โUser() function is used to get the logged-in user
What is the use of DB facade?
โDB facade is used to run SQL queries like create, select, update, insert, and delete.
How to check request is ajax or not ?
โIn Laravel, we can use $request->ajax() method to check request is ajax or not.
Name the Template Engine utilized by Laravel.
โBlade is a powerful template engine utilized by Laravel.
How can we check the Laravel current version?
โOne can easily check the current version of Laravel installation using the -version option of artisan command.
What is laravel spark?
โSpark is a Laravel package that provides scaffolding for all of the stuff you don't want to code.
Explain Migrations in Laravel.
โLaravel Migrations are like version control for the 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 the applicationโs database schema.
Name aggregates methods of query builder.
โAggregates methods of query builder are:
- max()
- min()
- sum()
- avg()
- count()
What is Monolog library in Laravel?
โLaravel utilizes the Monolog library, which provides support for a variety of powerful log handlers.
What is a Controller?
โA controller is the "C" in the "MVC" (Model-View-Controller) architecture, which is what Laravel is based on.
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.
Which class is used to handle exceptions?
โLaravel exceptions are handled by App\Exceptions\Handler class.
Explain collections in Laravel.
โCollections is a wrapper class to work with arrays.
How can someone turn off CSRF protection for a specific route?
โTo turn off CSRF protection for a specific route, we can add that specific URL or Route in $except variable which is present in the app\Http\Middleware\VerifyCsrfToken.phpfile.
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.
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.
How can you 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.
Explain listeners.
โListeners are used to handling events and exceptions. The most common listener in Laravel for login event is LoginListener.
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.
What is Redis?
โ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.
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.
Explain reverse routing in Laravel.
โReverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible.
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).
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.
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.
What is the deployer?
โDeployer provides a turn-key Kubernetes-based application management platform that accelerates the adoption of open-source and cloud-native technologies.
What do you know about CSRF token in Laravel?
โCSRF protection stands for Cross-Site Request Forgery protection. CSRF detects unauthorized attacks on web applications by the unauthorized users of a system. The built-in CSRF plug-in is used to create CSRF tokens so that it can verify all the operations and requests sent by an active authenticated user.
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.
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.
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.
How to hash password in Laravel?
โThe Hash::make function is used to create a hash for the password.
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.
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.
How to Install Laravel via Composer?
โcomposer create-project --prefer-dist laravel/laravel myproject
How to Install Lumen via Composer?
โcomposer create-project --prefer-dist laravel/lumen myproject
How to clear Cache in Laravel?
โYou can use php artisan cache:clear commnad to clear Cache in Laravel.
What is a fluent query builder in Laravel?
โThe Fluent Query Builder is Laravel's powerful fluent interface for building SQL queries and working with your database.
What are policies classes?
โPolicies classes include authorization logic of Laravel application. These classes are used for a particular model or resource.
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.
What is Route Model Binding?
โ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.
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.
How to compare two Carbon Timestamps?
โFirst, Eloquent automatically converts its timestamps ( created_at, updated_at ) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property: protected $dates = ['edited_at'];
Explain homestead in the Laravel.
โHomestead is basically an official, pre-packaged, and vagrant virtual machine that is used to deliver Laravel developers and all the necessary tools in order to develop Laravel out of the box. This machine is also known to include Ubuntu, Gulp, Bower, and various other development tools that are useful in developing full-scale web applications.
Explain Laravelโs Middleware.
โAs the name suggests, Middleware acts as a middleman between request and response. It is a type of filtering mechanism. 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.
What is service container in Laravel?
โService container is a tool used for performing dependency injection in Laravel.
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.
What is MVC framework?
โIt is Model, View, and Controller:
- Model: Model defines logic to write Laravel application.
- View: It covers the UI logic of Laravel application.
- Controller: It works as an interface between Model, and View. It is a way how the user interacts with an application.
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.
What are the disadvantages of using Laravel?
โ- 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-
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:
- Constructor injection
- Setter injection
- Interface injection.
What is namespace in Laravel?
โA namespace allows a user to group the functions, classes, and constants under a specific name.
How to remove a complied class file?
โUse clear-compiled command to remove the compiled class file.
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.
What is Lazy vs Eager Loading in Laravel?
โLaravel Eloquent ORM provides two type of loading.
- Lazy Loading: By default, accessing data in eloquent is "Lazy loaded"
- Eager Loading: This can be achieved using with() in Eloquent. Eager loading alleviates the N + 1 query problem.
How to rollback last migration?
โUse need to use artisan command to rollback the last migration.
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.
List some default packages provided by Laravel 5.4 ?
โ- Cashier
- Envoy
- Passport
- Scout
- Socialite
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.
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.
What is Laravel Envoyer?
โEnvoyer is a zero-down-time deployer for PHP & Laravel projects, which means it is a tool that you connect to your server to run your deploys, and which uses a series of tools to ensure that all of the preparation work each deploy needs in order to run.
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.
How to configure a mail-in Laravel?
โLaravel provides APIs to send an email on local and live server.
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:
- Numbers
- Addresses
- DateTime
- Payments
- Lorem text
How can you enable query log in Laravel?
โYou can use enableQueryLog method to enable query log in Laravel.
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.
How to create middleware in Laravel?
โphp artisan make: middleware
What is Closure in Laravel?
โA Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function.
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.
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.
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.
Define composer.
โIt is an application-level package manager for PHP. It provides a standard format for managing PHP software dependencies and libraries.
Laravel MCQ Quiz Interview Questions
Which of following Collection method returns all records from Laravel collection?
โ- A) ->all()
- B) ->get()
- C) ->where()
- D) ->whereAll()
Answer: A
View files in Laravel end in
โ- A) .blade.php
- B) .php
- C) .vue
- D) .blade
Answer: A
Which one is the Laravel command line interface?
โ- A) CLI
- B) php artisan
- C) composer
- D) git
Answer: B
Which artisan command is used to remove the compiled class file?
โ- A) clearcompiled
- B) clear compiled
- C) clear-compiled
- D) clear:all
Answer: C
Which directory contain โrobot.txtโ file ?
โ- A) app
- B) public
- C) config
- D) storage
Answer: B
What is Blade?
โ- A) Template Engine
- B) package
- C) view file
- D) framework
Answer: A
What is @yield used for?
โ- A) to display the contents of a given section.
- B) to extend an layout
- C) to include a file
Answer: A
Which command is used to start laravel server?
โ- A) php artisan serve
- B) php artisan start
- C) php artisan start-server
- D) php artisan project_name
Answer: A
Laravel is based on _____________________.
โ- A) MVVM Design Pattern
- B) MVC Design Pattern
- C) Singleton Design Pattern
- D) Composite Design Pattern
Answer: B
. Which of following methods are used in database migrations classes?
โ- A) execute() and rollback()
- B) up() and down()
- C) run() and delete()
- D) save() and update()
Answer: B
The vendor directory contains
โ- A) Laravel Framework code
- B) Assets
- C) Third-party code
- D) Configuration files
Answer: C
Artisan command to flush the application cache:
โ- A) cache:flush
- B) cache:clear
- C) cache:forget
- D) cache:remove
Answer: B