Laravel Interview questions For Freshers & Experienced

  • Question 1) What is Laravel?
  • Question 2) What is Laravel auth?
  • Question 3) How to use laravel or condition?
  • Question 4) What are Laravel Helpers?
  • Question 5) What are laravel traits?
  • Question 6) Where laravel logs are stored?
  • Question 7) What are Laravel Guards?
  • Question 8) How to clear cache in Laravel?
  • Question 9) What is Eloquent in Laravel?
  • Question 10) What is mass assignment and fillable in Laravel?
  • Question 11) Enlist few popular packages of Laravel?
  • Question 12) What is a facade in Laravel?
  • Question 13) How to enable Laravel maintenance mode?
  • Sharad Jaiswal
  • 21st Dec, 2019
  • 1053 Followers

Laravel Interview questions
Updated ON

21st Dec, 2019

No. of Questions

20

Posted In

PHP Frameworks

Author

Sharad Jaiswal

What is Laravel?

Laravel is a web application that eases out the common tasks used in the routing, authentication, caching and sessions with elegant and expressive syntax. Laravel makes the task of development simple without giving up application functionality. It is a PHP framework that follows the Model-View-Controller (MVC) pattern. Eloquent ORM, super-fast mechanism for authentication, blade templating, and superior routing and controllers are some of the best features of Laravel.

Inversion of Control (IoC) or service container is the most important rule to manage the class dependencies in Laravel. Laravel is a compilation of components to compose a modular application and cache all the data from view to the routes.

Key Features of Laravel

Below are few major features of Laravel

Inbuilt Authentication System

Eloquent ORM

Unit-Testing

MVC Architecture

Easily Scalable and Secure

Artisan

Database Migration

Easy Routing

Dependency Injection

Experienced Laravel interview Questions

Q1. What is Laravel?

Laravel is a open-source PHP framework, which is very easy to understand. Taylor Otwell is developer of laravel, it is released on june 2011. Laravel uses existing elements of contrasting frameworks.

The source code of Laravel is hosted on the GitHub and licensed under the terms of MIT License. It has wide range of functionalities including PHP framework like Codelgniter, Yii and other languages like Ruby on Rails, ASP.NET MVC , & Sinatra.

We can say that the development in Laravel must be an delightful, innovative, satisfying. 

Q2. What is Laravel auth?

Laravel auth (auth means authentication) is the process of recognizing the user credentials.Most websites will need a way to allow users to log in so that they can access resources , update information & so on.

Laravel makes implementing authentication very simple . The authentication fileis located at the config/auth.php , which carry some well docmented options for improving the behaviour of the authentication services.

By deafault , Laravel includes an App\User model in your app directory. This model may be used with the default driver. Eloquent is the default driver & you may also use the database authentication driver .

Q3. How to use laravel or condition?

Eloquent is the default driver in laravel , Eloquent is a great thing – you can build your step-by-step & then call get() method. However sometimes it is difficult for complex queries.

Lets take a example :

we need to filter male customers age 20+ or female customers aged 60+. Simple Eloquent query will be:

// . . .
$q->where(‘gender’, ‘male’);
$q->orWhere(‘age’,  ‘>=’ , 20);
$q->where(‘gender’, ‘female’);
$q->orWhere(‘age’,  ‘>=’ , 60);

Now look at the MYSQL query for this codition , it wouldn’t have any brackets :

...WHERE gender = ‘male’ and age >= 20 or gender = ‘female’  and age >= 60

Q4. What are Laravel Helpers?

Laravel include a range of Helpers (PHP function) that you can call anywhere within your application. They make your venture suitable for working .

You can also define helper by your own to avoid repeating in the same code. It ensures better maintainability of your application. It is convenient for doing things like working with arrays,file paths, strings, & routes , among other things like the dd() function.

Helper are grouped together based on the performance. List of Helper group is given below :

  • Arrays ( Arr::add , Arr::has , Arr::sort , Arr::collapse )
  • Paths ( app path , base path , mix , database path )
  • Strings ( Str::finish , Str::slug , Str::is , Str::snake )
  • URLs ( action , route , asset , url )
  • Miscellaneous ( abort , abort if , report , request)

Q5. What are laravel traits?

Trait is the mechanism for code reuse in single inheritance language i.e. PHP . Simply we can say that the a class can only inherit from one other class.

Trait , like an abstarct class, cannot be detect on it’s own . It’s great that we can write some code, reuse that again & again throughout our codebase more efficiently.

Creating a trait is very easy, there is not much code is required to create a trait. We will name the folder to store all my traits is Traits , using namespace App\Traits .

Now here we will show you the structure of trait , it has function called verifyAndStoreImage .

<?php

namespace App\Traits;

trait StoreImageTrait {
	
	public function  verifyAndStoreImage() {

	}

}

Q6. Where laravel logs are stored?

The Laravel logging facilities provide a simple layer on the top of the powerful Monolog library. By default , Laravel is configured to create a single log file.

File is stored in app/storage/logs/laravel.log

if you want to write the information in the log , so you can write as follows :

Log::info(‘information’);


Log::warning(‘warning’)


Log::error(‘error’)

Here are few most common log levels :-

  • E_ERROR :- Fatal run-time errors . These indicates errors that can not be recovered
  • E_WARNING :- Run_time warnings(non-fatal error). Execution of the script is not
  • E_PARSE :- Compile-time parse errors. Parse errors should only be generated by the
  • E_NOTICE :- Run-time notices. These indicate that the script encountered something

Q7. What are Laravel Guards?

A Guard is way of supplying the logic that is used to identify authenticated users . Laravel provides different guards like sessions and tokens. The session guard maintains the state of the user in each request by the cookies , and on the other hand , token guard authenticates the user by checking a valid token in every request.

Guard instruct laravel to store and retrieve the information about the users. You can define custom using the extend method on the facades . You have to place the call to extend in the service provider i.e.AuthServiceProvider.

<?php
namespace App\Providers;

use App\Services\Auth\JwtGuard;

use Illuminate\Support\Facades\Auth;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider
as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
	/**
	 * Register any
application authentication / authorization services.
	*
	* @return void
	*/
	 public function boot()
	{
		$this->registerPolicies();
		Auth::extend('jwt',
function ($app, $name, array $config) {
		// Return an instance of
Illuminate\Contracts\Auth\Guard...
		return new
JwtGuard(Auth::createUserProvider($config['provider']));
		});
	}
}

Q8. How to clear cache in Laravel?

We can clear cache in Laravel by the command line (CLI). In Larva projects we need to make cache for superior completion. However sometimes our application is development mode then we want to do is not to cured due to cache. This time we are facing a problem , so we have to clear the cache.

  • Clear Route cache :-
     php artisan route:cache
  • Clear Cache Laravel Application :-
     php artisan cache:clear
  • Laravel Clear Config Cache:-
     php artisan view:clear
  • Reoptimized Class:-
     php artisan optimize
  • Laravel Clear Cache on Shared Hosting Server :-
     Route::get(‘/clear-cache’, function() { 
	$exitCode = Artisan::call(‘cache:clear’);
	return “Cache is cleared”;
     });

Q9. What is Eloquent in Laravel?

Eloquent OMR(Object-relational Mapping) included with Laravel provides an attractive , simple Active record implementation for the working with database. Eloquent is object that is representative of your database and tables , in other words it’s act as controller between user and DBMS.

For eg,
 DB raw query,
select * from post LIMIT 1
 Eloquent equivalent,
$post = Post::first();
$post->column_name;

It’s way of representing your database values with objects you can easily use with your application.

Eloquent relationships are defined as methods on your Eloquent model classes :-

-> One To One - hasOne
-> One To Many - hasMany
-> One To Many(Inverse) - belongsTo
-> Many To Many - belongsToMany
-> Has Many Through – hasManyThrough
-> Polymorphic Relations
-> Many To Many Polymorphic Relation 

Q10. What is mass assignment and fillable in Laravel?

Mass assignment is a process of sending an array of data that will be saved to the specified model at once . In general, you don’t need to save the data on your model on one basis , but rather in a single process.

Mass assignment is good, but there are certain security problems behind it. What if someone passes a value to the model and without protection they can definitely modify all fields including the ID. That’s not good.

Fillable is the property of model, this property specifies which attributes in the table should be mass-assignable.

protected $fillable = [‘first_name’ , ‘last _name’, ‘email’];

for example let’s say you have a user model with :-
  
protected $hidden = array(‘password’);
protected $fillable = [‘username’ , ‘email’];

and for your registration logic you have something like :

$user = new User( [ ‘username’ => Input::get(‘username’) ,
‘email’ => Input::get(‘email’), ] ) ;

$user ->password = Hash::make(Input::get(‘password’));

Q11. Enlist few popular packages of Laravel?

Laravel packages are used for developing web applications , it offers easy & quick development . Few popular packages of laravel are :-

  1. Spatie
  2. Entrust
  3. Laravel Debugbar
  4. Laravel User Verification
  5. Socialite
  6. Laravel Mix
  7. Eloquent-Sluggable
  8. Migration Generator
  9. No Captcha
  10. Laravel GraphQL
  11. User verification
  12. Tinker
  13. Breadcrumbs
  14. Artisan View
  15. laravel backup

Q12. What is a facade in Laravel?

A facade is a class wrapping a complex library to provide a simple and more readable interface to it. Facade pattern is a softwarre design pattern that is oftn used in object oriented programming language .

The following are the steps to create facade in laravel :-

Step 1 :- Create PHP Class File.

Step 2:- Bind that class to Service Provider.

Step 3 :- Register that ServiceProvider to Config\app.php as providers

Config\app.php as providers

Step 4 :- Create Class which is this class extends to

lluminate\Support\Facades\Facade.

Step 5 :- Register point 4 to Config\app.php as aliases.

Q13. How to enable Laravel maintenance mode?

There are two ways to enable & disable maintenance mode in laravel 5. When your applications in maintenance mode , a custom view will be displayed for all requests into your application . This makes it easy to “disable” your application while it is updating or when you are performing maintenance . A maintenance mode check is included in the default middleware stack of your application is in maintenance mode , a MaintenanceModeException will be thrown with a status code of 503 .

  • To enable maintenance mode , execute the down Artisan command :- php artisan down
  • To disable maintenance mode , execute the up Artisan Command :- php artisan up

Q14. How to use laravel multiple where?

We have a simple way to use laravel multiple where by adding an array of condition where function of laravel Eloquent to create multiple where clauses . It works , but it’s not elegant .

Example :-

$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();

Here look at some other examples :-

$result=DB::table(‘users’)->where(array(
‘column1’ => value1,

‘column2’ => value2,

‘column3’ => value3))

->get();

Another way to creating scope :-

public function scopeActive($query)

{

    return $query->where('active', '=', 1);

}

public function scopeThat($query)

{

    return $query->where('that', '=', 1);

}

Then call the scope given below :

$users = User::active()->that()->get();

Q15. List types of relationships Laravel Supports?

Database tables are often related to one another .There are basically diffrent types of relationships are :-

  1. One to one
  2. One to many
  3. Many to many
  4. Has one through
  5. Has many through
  6. One to one (Polymorphic)
  7. One to many (Polymorphic)
  8. Many to many (Polymorphic)

Q16. What is Laravel nullable?

A field that is allowed to have no values is called nullable. It may be null variable , object , type , null column .

If someone wants to set the column in the table as null and he/she is doing on rollback up & on down function it will not work .

In the latest version of laravel 5 you will write it as :- 

$table->...->nullable(false)->change();

Q17. How to set session in Laravel?

Session in Laravel provides a wide range of inbuilt methods for setting the session data. In laravel , session is a parameter passing mechanism which help us to store the data across multiple requests.

In laravel there are some built in session drivers , some of them are given below :- File , cookie , database , apc , memcached , redis , array .

Setting a single variable in sesion :-

Syntax :- Session::put(‘key’ , ‘value’);

Example:- Session::put(‘email’ , $data[‘email’]);
	      Session::put(‘email’ , $email);
	      Session::put(‘email’ , ‘utkarshpaliwal111@gmail.com’);

Q18. Enlist few builtin string helpers in Laravel?

Laravel provides some pretty cool helper functions to make common tasks easier. Some of builtin string helpers in Laravel are given below :-

  • camel_case() make a camel Case string
  • class_basename() find the base class with no namespace
  • e() make htmlentities great again
  • ends_with() checks if the string ends with a given value
  • snake_case() turn a string into snake_case
  • str_limit() limit the length of a long string
  • starts with() check to see if a string begins with a value
  • str_contains() see if a string contains a value
  • str_finish() add a single value to a string
  • str_is() use wildcards to match a pattern
  • str_plural() turn a string into it’s plural form
  • str_singular() turn a plural string into it’s singular form
  • str_random() create a random string
  • str_slug() sluggify-a-string
  • studly case() turn a string into StudlyCase
  • title_case() Turn A String Into A Title

Q19. What are laravel named routes?

It is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.

Most of the routes for your application will be defined in the app/routes.php file. The simplest Laravel routes consist of a URI and a Closure callback.

Syntax of defining naming routes:-

We can define the named routes by chaining the name method onto the route definition:-

Basic GET Route :-

Route::get(‘/’,function()
{
	return ‘Hello world’;
});

Q20. What are collections in Laravel?

Laravel collections are very supreme distributor of the Laravel framework. They are what PHP arrays should be, but better.

The collection class implements some interfaces given below :-

  1. ArrayAccess
  2. IteratorAggregate
  3. JsonSerializable

Creating a new collection :-

we can create a new colection by observing the Illuminate\Support\Collection class.

Here is an easy example using the collect() helper method:

$newCollection = collect([1,2,3,4,5,6,7,8,9,10]);

some of available methods on the collection class are:-

  • all
  • average
  • avg
  • chunk
  • collapse
  • combine
  • concat
  • contains
  • map
  • count
  • sort
  • sortBy
  • some
  • split
  • keys
  • join
  • sum
  • max

About Author :

  • Author of Laravel Interview questions

    Sharad Jaiswal

    Sharad Jaiswal is Sr. Web Developer from Noida area. He have rich experience in PHP, Angular Js, React, javascript and Node .If you any query or project on these programming you can drop your enquiry in comment section.

2 comment(s) :

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.