Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Laravel Interview Questions and Answers

by Venkatesan M, on May 22, 2017 4:55:19 PM

Laravel Interview Questions and Answers

Q1. What is Laravel ?

Ans: 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.

Q2. List some official packages provided by Laravel?

Ans:

  • Cashier
  • Envoy
  • Passport
  • Scout
  • Socialite

Q3. List out latest features of Laravel.

Ans:

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

Q4. List out some benefits of Laravel over other Php frameworks.

Ans:  

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

Q5. What is composer ?

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

Q6. How to install laravel via composer ?

Ans: composer create-project laravel/laravel your-project-name version

Q7. How to check laravel current version ?

Ans: You can check the current version of your Laravel installation using the --version option of artisan command
Usages:-

php artisan --version

Q8. What is php artisan. List out some artisan command ?

Ans: 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

Q9. Explain Events in laravel ?

Ans: 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.

Q10. How to enable query log in laravel?

Ans: Use the enableQueryLog method:

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

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

$queries = DB::getQueryLog();

 

Q11. How to turn off CRSF protection for a route in Laravel?

Ans: 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);
}

Q12. What is Lumen?

Ans: 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.

Q13. What are laravel facades?

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

});

Q14. What are laravel Contracts?

Ans: Laravel's Contracts are nothing but  set of interfaces that define the core services provided by the Laravel framework.

Q15. Explain Laravel service container ?

Ans: 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.

You can read  more about Laravel from here 

Q16. How can you get users IP address  in Laravel ?

Ans: public function getUserIp(Request $request){

// Getting ip address of remote user

return $user_ip_address=$request->ip();

}

Q17. How to use custom table in Laravel Modal ?

Ans: 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";


Q18. What is Laravel Eloquent?

Ans: 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";

}

Q19. How to define Fillable Attribute in Laravel Modal ?

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

}

Q20. What is in vendor directory of Laravel ?

Ans: Any packages we pulled from composer is kept in vendor directory of laravel.

Q21. In which directory controllers are located in Laravel ?

Ans: We kept all controllers in

app/http/Controllersdirectory

Q22. What does PHP compact function do ?

Ans: 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.

Q23. Define ORM ?

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

Q24. How to create a record in Laravel using eloquent? ?

Ans: 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();

Q25. List some Aggregates methods provided by query builder in Laravel

Ans:

  • count()
  • max()
  • min()
  • avg()
  • sum()

Q26. What is the purpose of the Eloquent cursor() method in laravel ?

Ans: 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

}

Q27. How to get Logged in user info in laravel ?

Ans: Auth::User() function is used to get Logged in user info in laravel.
Usage:-

if(Auth::check()){

$loggedIn_user=Auth::User();

dd($loggedIn_user);

}

Q28. What are Closures in laravel ?

Ans: 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.

Q29. What are Advantages of Laravel?

Ans:

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel

Q30. What are the feature of Laravel5.0?

Ans:

  • Method injection
  • Contracts
  • Route caching
  • Events object
  • Multiple file system
  • Authentication Scaffolding
  • dotenv – Environmental Detection
  • Laravel Scheduler

Q31. Compare Laravel with Codeigniter?

Ans:

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.

 

Q32. What are Bundles,Reverse Routing and The IoC container ?

Ans:

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.

Q33. How to set Database connection in Laravel?

Ans: 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'    => '',

],

Q34. How to enable the Query Logging?

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

Q35. How to use select query in Laravel?

Ans: $users = DB::select('select * from users where city_id = ?', 10);

if(!empty($users)){

foreach($users as $user){

}

}

Q36. How to use Insert Statement in Laravel?

Ans: DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]);

Q37. How to use Update Statement in Laravel?

Ans: DB::update('update users set city_id = 10 where id = ?', [1015]);

Q38. How to use Update Statement in Laravel?

Ans: DB::update('update users set city_id = 10 where id = ?', [1015]);

Q39. How to use delete Statement in Laravel?

Ans: DB::delete('delete from  users where id = ?', [1015]);

Q40. Does Laravel support caching?

Ans: Yes, Its provides.

Q41. What is HTTP middleware?

Ans: 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.

Q42. What is database migration? And how to use it to add insert initial data to database?

Ans: 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.

Q43. What directories that need to be writable laravel installation?

Ans: 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.

Q44. How to implement you own package in Laravel?

Ans: You can create a package in laravel using the following steps:

  • Package folder and name
  • Composer.json file for the package
  • Loading package via main composer.json and PSR-4
  • Creating a Service Provider
  • Create a Controller for your package
  • Create our Routes.php file

Q45. What are the main differences between Laravel 4 and Laravel 5.x?

Ans: Summarizing Laravel 5.0 Release notes from the above article:

  • The old app/models directory has been entirely removed.
  • Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory.
  • A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x.
  • Application language files and views have been moved to the resources directory.
  • All major Laravel components implement interfaces which are located in the illuminate/contracts repository.
  • New route:cache Artisan command to drastically speed up the registration of your routes.
  • Laravel 5 now supports HTTP middleware, and the included authentication and CSRF "filters" have been converted to middleware.
  • you may now type-hint dependencies on controller methods.
  • 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.
  • You may now define events as objects instead of simply using strings.
  • 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.
  • 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.
  • 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.
  • The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP.
  • Laravel 5 now utilizes DotEnv by Vance Lucas.
  • Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets.
  • Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers.
  • 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!
  • 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.
  • The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests.
  • new Artisan generator commands have been added to the framework.
  • The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.

Q46. What is routing and how, and what are the different ways to write it?

Ans: 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.

Related Interview Questions...

Topics:Laravellaravel interview questionsInformation Technologies (IT)

Comments

Subscribe

Top Courses in Python

Top Courses in Python

We help you to choose the right Python career Path at myTectra. Here are the top courses in Python one can select. Learn More →

aathirai cut mango pickle

More...