Laravel Interview Questions and Answers
by Bharathkumar, on Sep 10, 2022 12:50:19 PM
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. List some official packages provided by Laravel?
- Cashier
- Envoy
- Passport
- Scout
- Socialite
3. List out latest features of Laravel.
- 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.
4. List out some benefits of Laravel over other Php frameworks.
- 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.
5.What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.
6. How to install laravel via composer ?
composer create-project laravel/laravel your-project-name version
7.How to check laravel current version ?
You can check the current version of your Laravel installation using the –version option of artisan command
Usages:-
php artisan –version
8. What is php artisan. List out some artisan command ?
PHPartisanis 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 modal modal_name
- php artisan make controller controller_name
9. Explain Events in laravel ?
An event is anincident 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.
Below are some events examples in laravel :-
- A new user has registered
- A new comment is posted
- User login/logout
- New product is added.
10.How to enable query log in laravel?
Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();
11.How to turn off CRSF protection for a route in Laravel?
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);
}
12.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.
13. 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 Facadesserve 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 Illuminate\Support\Facades namespace. You can easily access a Facade like so:
use Illuminate\Support\Facades\Cache;
Route::get(‘/cache’, function () {
return Cache::get(‘key’);
});
14.What are laravel Contracts?
Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravel framework.
15. 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.
16. How can you get users IP address in Laravel ?
public function getUserIp(Request $request){
// Getting ip address of remote user
return $user_ip_address=$request->ip();
}
17. How to use custom table in Laravel Modal ?
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_user_table";
}
18.What is Laravel Eloquent?
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.
rotected $table=”my_user_table”;
}
19. How to define Fillable Attribute in Laravel Modal ?
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’);
}
20.What is in vendor directory of Laravel ?
Any packages we pulled from composer is kept in vendor directory of laravel.
21. In which directory controllers are located in Laravel ?
We kept all controllers in
app/http/Controllersdirectory
22 .What does PHP compact function do ?
PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.
23.. Define ORM ?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
24 .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();
25 . List some Aggregates methods provided by query builder in Laravel
- count()
- max()
- min()
- avg()
- sum()
26 .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 Usage
foreach (Product::where(‘name’, ‘bar’)->cursor() as $flight) {
//do some stuff
}
27 . 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);
}
28. What are Closures in laravel ?
Closures is 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.
29.What are Advantages of Laravel?
- Easy and consistent syntax
- Set-up process is easy
- customization process is easy
- code is always regimented with Laravel
30.What are the feature of Laravel5.0?
- Method injection
- Contracts
- Route caching
- Events object
- Multiple file system
- Authentication Scaffolding
- dotenv – Environmental Detection
- Laravel Scheduler
31. Compare Laravel with Codeigniter?
Laravel | Codeigniter |
Laravel is a framework with expressive, elegant syntax | CodeIgniter is a powerful PHP framework |
Development is enjoyable, creative experience | Simple and elegant toolkit to create full-featured web applications. |
Laravel is built for latest version of PHP | Codeigniter is an older more mature framework |
It is more object oriented compared to CodeIgniter. | It is less object oriented compared to Laravel. |
Laravel community is still small, but it is growing very fast. | Codeigniter community is large. |
32.What are Bundles,Reverse Routing and The IoC container ?
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.
33.How to set Database connection in Laravel?
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’ => ”,
],
34. How to enable the Query Logging?
DB::connection()->enableQueryLog();
35. How to use select query in Laravel?
$users = DB::select(‘select * from users where city_id = ?’, 10);
if(!empty($users)){
foreach($users as $user){
}
}
36. How to use Insert Statement in Laravel?
DB::insert(‘insert into users (id, name, city_id) values (?, ?)’, [1, ‘Web technology’,10]);
37. How to use Update Statement in Laravel?
DB::update(‘update users set city_id = 10 where id = ?’, [1015]);
38. How to use Update Statement in Laravel?
DB::update(‘update users set city_id = 10 where id = ?’, [1015]);
39. How to use delete Statement in Laravel?
DB::delete(‘delete from users where id = ?’, [1015]);
40.Does Laravel support caching?
Yes, Its provides.
41.What is HTTP middleware?
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.
42.What is database migration? And how to use it to add insert initial data to database?
Migrations are like version control for your database, allowing 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. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.
Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.
43. What directories that need to be writable laravel installation?
After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.
44.How to implement you own package in Laravel?
You can create a package in laravel using the following steps:
1. Package folder and name
2. Composer.json file for the package
3. Loading package via main composer.json and PSR-4
4. Creating a Service Provider
5. Create a Controller for your package
6. Create our Routes.php file
45.What are the main differences between Laravel 4 and Laravel 5.x?
Summarizing Laravel 5.0 Release notes from the above article: 1. The old app/models directory has been entirely removed.
2. Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory.
3. A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x.
4. Application language files and views have been moved to the resources directory.
5. All major Laravel components implement interfaces which are located in the illuminate/contracts repository.
6. New route:cache Artisan command to drastically speed up the registration of your routes.
7. Laravel 5 now supports HTTP middleware, and the included authentication and CSRF “filters” have been converted to middleware.
8. you may now type-hint dependencies on controller methods.
9. User registration, authentication, and password reset controllers are now included out of the box, as well as simple corresponding views, which are located at resources/views/auth.
10. You may now define events as objects instead of simply using strings.
11. In addition to the queue job format supported in Laravel 4, Laravel 5 allows you to represent your queued jobs as simple command objects. These commands live in the app/Commands directory.
12. A database queue driver is now included in Laravel, providing a simple, local queue driver that requires no extra package installation beyond your database software.
13. Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
14. The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP.
15. Laravel 5 now utilizes DotEnv by Vance Lucas.
16. Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets.
17. Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers.
18. Laravel now includes the powerful Flysystem filesystem abstraction library, providing pain free integration with local, Amazon S3, and Rackspace cloud storage – all with one, unified and elegant API!
19. Laravel 5.0 introduces form requests, which extend the Illuminate\Foundation\Http\FormRequest class. These request objects can be combined with controller method injection to provide a boiler-plate free method of validating user input.
20. The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests.
21. new Artisan generator commands have been added to the framework.
22. The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.
46. What is routing and how, and what are the different ways to write it?
All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group. For most applications, you will begin by defining routes in your routes/web.php file.