PHP Laravel Interview Questions

PHP Laravel Interview Questions | Freshers & Experienced

  • Sharad Jaiswal
  • 23rd Nov, 2021
  • 471 Followers

About Php Laravel

Laravel is an open-source PHP framework created for the purpose of enhancing the development of web applications. It is consists of a robust collection of tools with expressive and graceful syntaxes. Laravel follows the model-view-controller (MVC) architectural pattern and the features like modular packaging system, access to relational databases, etc. make it popular among the developers, as the web application becomes more scalable and considerable time is saved, owing to the Laravel framework. Laravel offers a rich set of functionalities that incorporates the basic features of PHP frameworks like CodeIgniter, Yii, and other programming languages such as Ruby on Rails and also helps to save a lot of time if while developing a website from scratch.

finally, We have listed below the best PHP Laravel Interview Questions and Answers, which are very popular and asked various times in PHP Laravel Interview. So, practice these Laravel Interview Questions for the best preparation for your upcoming interview. We wish you good luck for a bright and prosperous future in Laravel.

Key Features of Php Laravel

Below are few major features of Php Laravel

Inbuilt Authentication System

Eloquent ORM

Unit-Testing

MVC Architecture

Easily Scalable and Secure

Artisan

Database Migration

Easy Routing

Dependency Injection

PHP Laravel Interview Questions for 1, 2, 3, 4, & 5 Years Experience.

Q1. What are pros and cons of using Laravel Framework?

Pros of Laravel

  1. It uses Blade template engine that helps in speed up compilation tasks and writing cleaner code.
  2. Bundled modularity forces code reusability.
  3. Easy to understand Eloquent ORM.
  4. Outstanding Command Line Interface Artisan.
  5. Clean, clear easily understandable documentation.

Cons of Laravel

  1. Quite slow because of loading multiple vendors.
  2. Amature developers face some difficulties in staring, but once they are familiar it will be fun to code in Laravel.
  3. Community support is not as wide as a comparison to other frameworks.
  4. Upgrading framework is a headache.

Q2. What is Laravel service container?

Service Container in Laravel is a Dependency Injection Container and a Registry for the application. It is one of the most powerful tool for managing class dependencies and performing dependency injection.

Q3. How To Use Delete Query In Laravel ?

DB::table('table_name')->delete($id);

is the simplest way to delete a record in Laravel.

Q4. How To Use Update Query In Laravel ?

Updating a record in Laravel using Eloquent.

$user=User::where(['id'=>1])->first();
$user->name='abc';
$user->age='22';
$user->save();

Q5. What is Laravel Dusk?

Laravel Dusk is browser automation and testing tool introduced in Laravel 5.4. It uses ChromeDriver to perform browser automation testing.

Q6. What is Laravel Echo?

Laravel Echo is a tool that makes it easy for you to bring the power of WebSockets to your Laravel applications. It simplifies some of the more common—and more complex—aspects of building complex WebSockets interactions.

Echo comes in two parts: a series of improvements to Laravel's Event broadcasting system, and a new JavaScript package.

Q7. What is Laravel Homestead ?

Laravel Homestead is an official, pre-packaged Vagrant "box" that provides you a wonderful development environment without requiring you to install PHP, HHVM, a web server, and any other server software on your local machine.

Q8. What is Tagging?

Tagging is a package in Laravel that allow you to tag your content like pages/ post to a keyword.

Q9. What is dependency injection in Laravel ?

Dependency injection or (D.I) is a technique in software Engineering whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). Injection is the passing of dependency to a dependent object (a client) that would use it.

Basically, You can found 3 types of dependency injection:

  • Constructor injection
  • Setter injection
  • Interface injection

Q10. What are named routes in Laravel?

Named routing is another amazing feature of the 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:

Example:

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

Q11. What are Laravel eloquent?

Eloquent is an ORM in Laravel that implements active record pattern and is used to interact with relational databases.

Eloquent OMR(Object-relational Mapping) included with Laravel provides an attractive, simple Active record implementation for working with the database. Eloquent is an object that is representative of your database and tables, in other words, it acts as a 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 a 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 

Q12. What is Lumen?

Lumen is micro-framework by Laravel. It is developed by the creator of Laravel Taylor Otwell for creating smart and blazing fast API’s. Lumen is built on top components of Laravel. As Lumen is a micro-framework not a complete web framework like Laravel and used for creating API’s only, so most of the components as HTTP sessions, cookies, and templating are excluded from Lumen and only features like routing, logging, caching, queues, validation, error handling, database abstraction, controllers, middleware, dependency injection, Blade templating, command scheduler, the service container, and the Eloquent ORM are kept.

Q13. What is a Facade?

In Programming, Facade is a software design pattern which is often used in object-oriented programming. Laravel facade is a class which provides a static-like interface to services inside the container.

Q14. How To Use Delete Statement In Laravel?

Use delete statement in Laravel:

In Query Builder Way:

\DB::table('users')->delete($id); // delete with id
\DB::table('users')->where('name', $name)->delete(); \\ delete with where condition

In Eloquent Way:

 User::find($id)->delete() // delete with id
 User::where(['name'=>$name])->delete();  \\ delete with where condition

Q15. Difference between Contracts and Facades?

Contracts are an interface, while Facades are not an interface. it is a class. 

Contracts are a set of interfaces that define the core services provided by the framework, while Facades provide a static interface to classes that are available in the application's service container.

 

Q16. What is an Observer in Laravel?

In Laravel, the Observers are used to group event listeners for a model. These methods receive the model as their only argument. Laravel does not include a default directory for observers.

Q17. How to get current Url in Laravel ?

In Laravel 5.5 or above you can use url()->current(); to get current URL without query string and  url()->full(); with the query string.

Q18. How To Use Select Query In Laravel?

DB::select('name')->table('users')->get();

This will create a collection that only contains the 'name' property of ever user...

DB::select('name','username')->table('users')->get();

This will select name and username from users

Q19. Which template engine Laravel use ?

Laravel uses Blade template Engine.

Q20. How to use custom table in Laravel Model ?

To use custom table name in Laravel Model add below code to your Model file.

protected $table = 'custom_table_name';

Q21. What are Closures in laravel ?

A Closure is an anonymous function that often used as callback methods and can be used as a parameter in a function.

Example of Laravel Closure

User::with('profile', function ($builder) {
	// Get me all collapsed comments
	return $builder->whereCollapsed(true);
	
});

Q22. How to get Logged in user info in Laravel ?

You can use Auth Facade to get logged in user information in Framework.

Example

<?php 
$userInfo= Auth::user();
echo $userInfo->id;
echo $userInfo->name;
dd( $userInfo);
?>

Q23. Does laravel support php 7?

Yes, Laravel supports PHP 7.

Q24. What is Laravel Elixir ?

Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports several common CSS and JavaScript pre-processors, and even testing tools. Using method chaining, Elixir allows you to fluently define your asset pipeline.

Laravel Elixir Example

elixir(function(mix) {
    mix.sass('app.scss')
       .coffee('app.coffee');
});

Q25. How can you display HTML with Blade in laravel ?

Blade template engine provides an easy and clean way to display HTML in the Laravel view. Use {!! $your_variable !!} in your view.

Q26. How to install Laravel via composer? Syntax

Use the below command to install or new project in Laravel.

composer create-project Laravel/Laravel your-project-name version

Note: The composer must be installed globally to run the above command.

Q27. What are Cookies ? How to get , set , destroy cookies in Laravel ?

Cookies are a small amount of data sent from specific websites to the clients computers. Cookies are stored on user computer using browsers. Cookies are important for working with the user's session on a web application.

In Laravel, you can create cookie using Cookie helper. Cookie helper is a global helper and an instance of Symfony\Component\HttpFoundation\Cookie class.

Setting Cookie in Laravel.

<?php 
	$cookie_name="user_name";
	$cookie_value="PhpScots";
	$cookie_expired_in=3600;//in mins
	$cookie_path='/'; // available to all pages of website.
	$cookie_host=$request->getHttpHost(); // domain or website you are $http_only=false;
	$my_cookie= cookie($cookie_name, $cookie_value,$cookie_expired_in,$cookie_path,$cookie_host,$http_only);
	return response()->withCookie($my_cookie);
?>

Getting Cookie in Laravel.

<?php
	return Cookie::get('cookie_name');
?>

Destroying Cookie in Laravel.

<?php
$cookie = Cookie::forget('cookie_name');
?>

Q28. How can you Exclude URIs From CSRF Protection in Laravel ?

You can Exclude URIs From CSRF Protection in Laravel by editing app/Http/Middleware/VerifyCsrfToken. You should place these routes outside of the web middleware group that the App\Providers\RouteServiceProvider applies to all routes in the routes/web.php file

Q29. What getFacadeAccessor method does?

Laravel Facades are another way to use classes without manually creating an object of the class. Examples of Laravel Facades are DB, Cache, Cookie, etc.

getFacadeAccessor() method in Laravel is used to return the name of a service container binding.

Example:

class ABC extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'abc'; }
}

In the above example whenever the user calls any static method on ABC class then Laravel automatically resolves the abc class binding from the service container and runs the requested method/function against that object.

Q30. What is Laravel?

Laravel is an open-source PHP framework, which is very easy to understand. Taylor Otwell is the developer of Laravel, it is released in June 2011. Laravel uses existing elements of contrasting frameworks.

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

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

Q31. 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 file is located at the config/auth.php, which carries some well-docmented options for improving the behaviour of the authentication services.

By default, 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.

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

Let's take an example :

we need to filter male customers age 20+ or female customers aged 60+. A 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 condition , it wouldn’t have any brackets :

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

Q33. What are Laravel Helpers?

Laravel includes 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 on 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.

The helper is grouped together based on the performance. The 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)

Q34. What are laravel traits?

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

Trait, like an abstract class, cannot be detected on its 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 as Traits, using namespace App\Traits.

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

<?php

namespace App\Traits;

trait StoreImageTrait {
	
	public function  verifyAndStoreImage() {

	}

}

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

The 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 a few most common log levels:-

  • E_ERROR:- Fatal run-time errors. This 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

Q36. What are Laravel Guards?

A Guard is a 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, the token guard authenticates the user by checking a valid token in every request.

Guard instructs travel 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']));
		});
	}
}

Q37. 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 in 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”;
     });

Q38. 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 the 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’));

Q39. 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-Pluggable
  8. Migration Generator
  9. No Captcha
  10. Laravel GraphQL
  11. User verification
  12. Tinker
  13. Breadcrumbs
  14. Artisan View
  15. laravel backup

Q40. 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. The facade pattern is a software design pattern that is often used in an object-oriented programming language.

The following are the steps to create a 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.

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

Q42. How to use laravel multiple where?

We have a simple way to use laravel multiple whereby adding an array of conditions where the 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();

Q43. List types of relationships Laravel Supports?

Database tables are often related to one another. There are basically different 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)

Q44. What is Laravel nullable?

A field that is allowed to have no values is called nullable. It may be a 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();

Q45. How to set session in Laravel?

Session in Laravel provides a wide range of inbuilt methods for setting the session data. In laravel, the session is a parameter passing mechanism that helps 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 session :-

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

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

Q46. Enlist few builtin string helpers in Laravel?

Laravel provides some pretty cool helper functions to make common tasks easier. Some of the built-in 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

Q47. 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 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’;
});

Q48. What are collections in Laravel?

Laravel collections are the 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 collection 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 the available methods in 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 PHP Laravel Interview Questions

    Sharad Jaiswal

    My name is Sharad Jaiswal, and I am the founder of Conax web Solutions. My tech stacks are PHP, NodeJS, Angular, React. I love to write technical articles and programming blogs.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.