Loading…

Laravel Interview Questions

Laravel Interview Questions

Laravel is a free and open-source PHP framework that follows the model–view–controller design (MVC) pattern. Our extensive collection of Laravel Interview Questions will help you find a great job. Laravel is a popular PHP framework that reduces the cost of development and improves code quality. Using Laravel, developers can save hours of development time and cut thousands of lines of code as compared to raw PHP. Because Laravel reuses the existing components of different frameworks in designing web applications, the outcome is more structured and pragmatic.

A Quick Overview of Laravel

About Laravel
What is Laravel Laravel is a free and open-source PHP framework that follows the model–view–controller design pattern.
Latest Version 6.0, released on 3rd September 2019
Created By Taylor Otwell
Laravel Follows MVC architectural pattern
Written in Laravel is written in the PHP language.
Laravel Licence MIT License

Development History

Laravel was created by Taylor Otwell. Laravel's first beta version was released on June 2011. Laravel 2 was released on September 2011. Laravel 3 was released in February 2012. Laravel 4 was released on May 2013. The majority of candidates are asked this information in laravel interview questions and answers. Laravel 6 was released on 3rd September 2019.

Key points about Laravel

  • Source code hosted on GitHub and licensed under MIT License.
  • Most Starred PHP Framework for custom software development on Github.
  • Its ability to use all of the new features of PHP sets it apart.
  • Friendly online community
  • Detailed documentation

Latest Recommended Version: The latest version is 6.0

Looking for a new job? Do not miss to read our Laravel Interview Questions.

Advantages of Laravel

  • It offers a rich set of functionalities.
  • Saves time.
  • The website built in Laravel is more scalable and secure.
  • Includes namespaces and interfaces that help to organize resources.
  • Provides a clean API.

You can visit our youtube video and this is very helpful in cracking your Laravel interview https://www.youtube.com/watch?v=WmwCBDx0fOk

We have put together all the popular Laravel interview questions and answers that will come in handy if you want to crack your next interview. This exhaustive list also contains Laravel 5 interview questions. These will be valuable in clearing job interviews as well as getting promotions at work.

Last update: 17 Nov 2019, 104 Questions and Answers

Most Frequently Asked Laravel Interview Questions And Answers With Examples:

It is a free, powerful and open-source PHP framework that follows the model–view–controller design pattern. It is a very popular framework which is developed in PHP, and that reduces the cost of development and improves code quality. It is produced by Taylor Otwell. The first version of laravel is released on 9 June 2011.

Features of Laravel
  • Eloquent ORM
  • Query builder available
  • Reverse routing
  • Restful controllers
  • Migrations
  • Database Seeding
  • Automatic pagination
  • Unit testing
  • Homestead
You can also read: Mysql Interview Questions
209 17

The latest version 6.0 is incorporated with a number of latest features such as Laravel vapor compatibility, semantic visioning, job middleware, lazy collections, eloquent sub-query enhancements, Laravel users interface, etc. The Laravel 6.0 released on 3rd September 2019 with latest and unique features.

Advanced Features of Laravel 6.0
  • Laravel Vapor Compatibility
  • Semantic Versioning
  • Job Middleware
  • Laravel User Interface (UI)
  • Eloquent Subquery Enhancements
  • Improved Authorization Responses
  • Lazy Collections
20 1
  • PHP version >= 7.2.0
  • JSON PHP Extension
  • BCMath PHP Extension
  • Ctype PHP Extension
  • Mbstring PHP Extension
  • XML PHP Extension.
  • Tokenizer PHP Extension
  • OpenSSL PHP Extension
  • PDO PHP Extension
16 3
Laravel installation steps:-
  • Download composer from https://getcomposer.org/download (if you don’t have a composer on your system)
  • Open cmd
  • Goto your htdocs folder.
  • C:\xampp\htdocs>composer create-project laravel/laravel projectname
    OR
    If you install some particular version, then you can use
    composer create-project laravel/laravel project name "5.6"

If you did not mention any particular version, then it will install with the latest version.

Related Article: How to install laravel
79 13

In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.

Example: If a user is not authenticated and it is trying to access the dashboard then, the middleware will redirect that user to the login page.

Get ready to be answerable to this question. This is a favorite Laravel Interview Questions of many interviewers. Don’t let this question waste the opportunity. Read it twice.

Example

                                                    

// Syntax
php artisan make:middleware MiddelwareName

// Example
php artisan make:middleware UserMiddelware

Now UserMiddelware.php file will create in app/Http/Middleware

88 3

It is a type of version control for our database. It is allowing us to modify and share the application's database schema easily.

A migration file contains two methods up() and down().

up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.

Example

                                                    

You can generate a migration & its file with the help of make:migration .

Syntax : php artisan make:migration blog

A current_date_blog.php file will be create in database/migrations

42 2

Reverse routing is generated URL’s based totally on route. It makes our application so a lot greater flexible.

Example

                                                    

Route:: get(‘login’, ‘login@index’); // It is normal route but after reverse routing, we can also call this link with
{{ HTML::link_to_action('login@index') }}

27 12

In between head, tag put <meta name="csrf-token" content="{{ csrf_token() }}"> and in Ajax, we have to add
$.ajaxSetup({
   headers: {
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

6 2

In Laravel, service providers are the center of overall Laravel application bootstrapping. User applications, as well as core services of Laravel, are bootstrapped with service providers. These powerful tools are used by developers to manage class dependencies and perform dependency injection. To create a service provider, we have to use the below-mentioned artisan command.

 

You can use php artisan make: provider ClientsServiceProvider artisan command to generate a service provider :

It has below listed functions in its file.
  • register function
  • boot function
49 11

In Laravel, we can use whereBetween() function to get data between two dates.

Example

                                                    

Blog::whereBetween('created_at', [$dateOne, $dateTwo])->get();

50 6

We can add that particular URL or Route in $except variable. It is present in the app\Http\Middleware\VerifyCsrfToken.php file.

 

Point to be noted: The question is mostly asked in Laravel Interview Questions. Read it twice and analyze the answers.

 

Example

                                                    

class VerifyCsrfToken extends BaseVerifier {
      protected $except = [
            'Pass here your URL',
      ];
}

46 6
How to create a Stored Procedure

To create a Stored Procedure you can execute given code in your MySQL query builder directly or use phpmyadmin for this.

DROP PROCEDURE IF EXISTS `get_subcategory_by_catid`;
delimiter ;;
CREATE PROCEDURE `get_subcategory_by_catid` (IN idx int)
BEGIN
SELECT id, parent_id, title, slug, created_at FROM category WHERE parent_id = idx AND status = 1 ORDER BY title;
END
;;
delimiter ;

After this, you can use this created procedure in your code in Laravel.

How to use stored procedure in Laravel

$getSubCategories = DB::select(
   'CALL get_subcategory_by_catid('.$item->category_id.')'
);

28 18

In Laravel, Facades offer a static interface to classes available inside the application's service container. They serve as static proxies for underlying classes present in the service container, offering benefit of expressive syntax while maintaining more flexibility and testability than other available traditional static methods.

All the facades are defined in the namespace Illuminate\Support\Facades for easy accessibility and usability.

Example

                                                    

use Illuminate\Support\Facades\Cache;

     Route::get('/cache', function () {

     return Cache::get('PutkeyNameHere');

});

20 9

It is a helper function which is used to dump a variable's contents to the browser and stop the further script execution. It stands for Dump and Die.

Example

                                                    

dd($array);

38 2

We can create a helper file using Composer. Steps are given below:-

  • Please create a "app/helpers.php" file that is in app folder.
  • Add
    "files": [
        "app/helpers.php"
    ]

    in "autoload" variable.
  • Now update your composer.json with composer dump-autoload or composer update
24 7

Artisan is a type of the "command line interface" using in Laravel. It provides lots of helpful commands for you while developing your application. We can run these command according to our need.

Laravel supports various artisan commands like
  • php artisan list;
  • php artisan –version
  • php artisan down;
  • php artisan help;
  • php artisan up;
  • php artisan make:controller;
  • php artisan make:mail;
  • php artisan make:model;
  • php artisan make:migration;
  • php artisan make:middleware;
  • php artisan make:auth;
  • php artisan make:provider etc.;
23 2
  • Run this "php artisan make:rule OlympicYear"
  • After that command it generates a file app/Rules/OlympicYear.php
  • We can write rule in the passes() in OlympicYear.php generated file. It will return true or false depending on condition, which is this in our case
    public function passes($attribute, $value)
    {
    return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
    }
  • Next, we can update error message to be this:
    public function message()
    {
    return ':attribute should be a year of Olympic Games';
    }
  • Finally, we use this class in controller's store() method we have this code:
    public function store(Request $request)
    {
    $this->validate($request, ['year' => new OlympicYear]);
    }
13 3

{{ $username }} is simply used to display text contents but {!! $username !!} is used to display content with HTML tags if exists.

40 2

Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection. It is also known as the IoC container. It offers several benefits to users such as.

Advantages of Service Container
  • Freedom to manage class dependencies on object creation.
  • Service contain as Registry.
  • Ability to bind interfaces to concrete classes.
11 3

1. Retrieving Data from session
session()->get('key');

2. Retrieving All session data
session()->all();

3. Remove data from session
session()->forget('key'); or session()->flush();

4. Storing Data in session
session()->put('key', 'value');

26 0
In case you are using save()

$blog = new Blog;
$blog->title = ‘Best Interview Questions’;
$blog->save()

// Now you can use (after save() function we can use like this)

$blog->id // It will display last inserted id

In case you are using insertGetId()

$insertGetId = DB::table(‘blogs’)->insertGetId([‘title’ => ‘Best Interview Questions’]);

14 1

Laravel provides a powerful and clean API over the SwiftMailer library with drivers for Mailgun, SMTP, Amazon SES, SparkPost, and send an email. With this API, we can send email on a local server as well as the live server.

Here is an example through the mail()

Laravel allows us to store email messages in our views files. For example, to manage our emails, we can create an email directory within our resources/views directory.

Example

                                                    
public function sendEmail(Request $request, $id)
    {
        $user = Admin::find($id);

        Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
            $m->from('info@bestinterviewquestion.com', 'Reminder');

            $m->to($user->email, $user->name)->subject('Your Reminder!');
        });
    }
10 1
1. How to set Cookie

To set cookie value, we have to use Cookie::put('key', 'value');

2. How to get Cookie

To get cookie Value we have to use Cookie::get('key');

3. How to delete or remove Cookie

To remove cookie Value we have to use Cookie::forget('key')

4. How to check Cookie

To Check cookie is exists or not, we have to use Cache::has('key')

11 2

Laravel Auth is the process of identifying the user credentials with the database. Laravel managed it's with the help of sessions which take input parameters like username and password, for user identification. If the settings match then the user is said to be authenticated.

Auth is in-built functionality provided by Laravel; we have to configure.

We can add this functionality with php artisan make: auth

Auth is used to identifying the user credentials with the database.

 

Key point: Freshers, this is very important for you all. It is one of the Laravel interview questions and answers you should know. It is asked in many interviews.

 

21 0

You can create a constants.php page in config folder if does not exist. Now you can put constant variable with value here and can use with Config::get('constants.VaribleName');

Example

                                                    
return [
    'ADMINEMAIL' => 'info@bestinterviewquestion.com',
];

Now we can display with

Config::get('constants.ADMINEMAIL');

13 1
There are sizable differences between laravel 4 and laravel 5 concerning LTS, features, file structures, etc.

Laravel four used to be the one who delivered large reputation to the Laravel framework, however this version no longer up to date anymore, and it also lacks a lot of functions released in Laravel 5.

  • Laravel 4 released May 2013 however Laravel 5 released in February 2015.
  • Laravel 5 has LTS Supports. It capability the LTS version stands for Long Term Support. It implies that bugfixes for that model will be provided for two years, till the next LTS version.
  • A new listing app/Providers replaces the app/start archives from preceding versions of Laravel 4.x.
  • Laravel 5 offers a Socialite bundle which is an optional, Laravel 5.0+ well matched package that provides painless authentication with OAuth providers.
  • The favored dd helper function, which dumps variable debug information, has been upgraded to use the incredible Symfony VarDumper.

In distinction to Laravel four to 5 version differences, which is huge, 5.x and 5.y variations are now not that different. Some features added, some updated/removed in laravel 5, but the core structure stays the same.

3 1

You can do this in various ways. Steps are given below:-

  • Copy .htaccess file from public folder and now paste it into your root.
  • Now rename server.php file/page to index.php on your root folder.
  • Now you can remove /public word from URL and refresh the page. Now it will work.
12 4

You can use request()->ip()

You can also use : Request::ip() but in this case we have to call namespace like this : Use Illuminate\Http\Request;

18 4
1. delete()

In case when we used to delete in Laravel then it removed records from the database table.

Example:

$delete = Post::where(‘id’, ‘=’, 1)->delete();

2. softDeletes()

To delete records permanently is not a good thing that’s why laravel used features are called SoftDelete. In this case, records did not remove from the table only delele_at value updated with current date and time.
Firstly we have to add given code in our required model file.

use SoftDeletes;
protected $dates = ['deleted_at'];

After this we can use both cases.

$softDelete = Post::where(‘id’, ‘=’, 1)->delete();

OR

$softDelete = Post::where(‘id’, ‘=’, 1)->softDeletes();

15 1

Our first step should be

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

After our query, it should be placed

$querieslog = DB::getQueryLog();

After that, it should be placed

dd($querieslog)

Example

                                                    

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

$result = User:where(['status' => 1])->get();

$log = DB::getQueryLog();

dd($log);

14 0

We have to call Facades in our controller file with this :
use Illuminate\Support\Facades\Storage;

Example

                                                    

if($request->hasFile(file_name')) {
      $file = Storage::putFile('YOUR FOLDER PATH', $request->file('file_name'));
}

10 5

Soft delete is a laravel feature that helps When models are soft deleted, they are not actually removed from our database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, we have to specify the softDelete property on the model like this.

In model we have to use namespace
use Illuminate\Database\Eloquent\SoftDeletes;

and we can use this
use SoftDeletes; in our model property.

After that when we will use delete() query then records will not remove from our database. then a deleted_at timestamp is set on the record.

This is the favorite interviewer question in Laravel interview questions.

12 2

The Eloquent ORM present in Laravel offers a simple yet beautiful ActiveRecord implementation to work with the database. Here, each database table offers a corresponding model which is used to interact with the same table. We can create Eloquent models using the make:model command.

It has many types of relationships.
  • One To One relationships
  • One To Many relationships
  • Many To Many relationships
  • Has Many Through relationships
  • Polymorphic relationships
  • Many To Many Polymorphic relationships

For more details you can visit www.Laravel.com

12 1

We have to use the following artisan commands to enable/disable maintenance mode.

Enable maintenance mode

php artisan down

Disable maintenance mode

php artisan up

7 0

In Laravel, dependency injection is a term used for the activity of injecting components into the user application. It’s a key element of agile architecture. The Laravel service container is a powerful tool that manages all class dependencies and performs dependency injection.

public function __construct(UserRepository $data)
{
    $this->userdata = $data;
}

In this given an example, the UserController needs to retrieve users data from a data source(database). So, we can inject a service that is able to recover all users. In this example, our UserRepository most likely uses Eloquent to get user’s data from the database.

6 4

We can create all web pages of our sites to tell Google and other search engines like Bing, Yahoo etc about the organization of our site content. These search engine web crawlers read this file to more intelligently crawl our sites.

Here are the steps that helps you to create real time sitemap.xml file and these steps also helps to create dynamic XML files.
  • Firstly we have to create a route for this in your routes/web.php file
    Example
    Route::get('sitemap.xml', 'SitemapController@index')->name('sitemapxml');
  • Now you can create SitemapController.php with artisan command php artisan make:controller SitemapController
  • Now you can put this code in your controller
    public function index() {
        $page = Page::where('status', '=', 1)->get();
        return response()->view('sitemap_xml', ['page' => $page])->header('Content-Type', 'text/xml');
    }
  • Now please create a view file in resources/view/sitemap_xml.blade.php file with this code
  • Put this code in that created view file
    <?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
       http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    @foreach ($page as $post)
       <url>
          <loc>{{ url($post->page_slug) }}</loc>
          <lastmod>{{ $post->updated_at->tz('UTC')->toAtomString() }}</lastmod>
          <priority>0.9</priority>
       </url>
    @endforeach
    </urlset>
3 1

Laravel provides a variety of aggregate functions such as max, min, count,avg, and sum. We can call any of these functions after constructing our query.

$users = DB::table(‘admin’)->count();
$maxComment = DB::table(‘blogs’)->max('comments');

5 0

We can use skip() and take() both methods to limit the number of results in the query. skip() is used to skip the number of results and take() is used to get the number of result from the query.

Example

                                                    

$posts = DB::table('blog')->skip(5)->take(10)->get();

// skip first 5 records
// get 10 records after 5

9 1

Views contain the HTML provided by our application and separate our controller or application logic from our presentation logic. These are stored in the resources/views directory.

Example

                                                    
<html>
<body>
    <h1>Best Interview Question<h1>
</body>
</html>
5 0

Faker is a type of module or packages which are used to create fake data for testing purposes. It can be used to produce all sorts of data.

It is used to generate the given data types.

  • Lorem text
  • Numbers
  • Person i.e. titles, names, gender, etc.
  • Addresses
  • DateTime
  • Phone numbers
  • Internet i.e. domains, URLs, emails etc.
  • Payments
  • Colour, Files, Images
  • UUID, Barcodes, etc

In Laravel, Faker is used basically for testing purposes.

3 1

Laravel 5.8 is the latest & current version. It releases on 26th February 2019; Bug Fixes Until August 26th, 2019 and Security Fixes Until February 26th, 2020.

Features of Laravel 5.8
  • Eloquent hasOneThrough relationships.
  • It has improved email validation.
  • Token Guard Token Hashing.
  • Convention based automatic registration of authorization policies.
  • DynamoDB cache and session drivers.
  • Mock or Spy Testing Helper Methods.
  • Improved scheduler timezone configuration.
  • Support for assigning multiple authentication guards to broadcast channels.
  • PSR-16 cache driver compliance.
  • Improvements to the artisan serve command.
  • PHPUnit 8.0 support.
  • Carbon 2.0 support.
  • Pheanstalk 4.0 support.
  • A variety of other bug fixes and usability improvements.
28 3
  • In Laravel, Queues are very useful for taking jobs, pieces of asynchronous work, and sending them to be performed by other processes and this is useful when making time-consuming API calls that we don’t want to make your users wait for before being served their next page.
  • Another advantage of using queues is that you don’t want to work the lines on the same server as your application. If your jobs involve intensive computations, then you don’t want to take risk those jobs taking down or slowing your web server.

 

 

6 0

Laravel Tinker is a powerful REPL tool which is used to interact with Laravel application with the command line in an interactive shell. Tinker came with the release of version 5.4 is extracted into a separate package.

How to install tinker

composer require laravel/tinker

How to execute

To execute tinker we can use php artisan tinker command.

5 4

Please run below artisan commands step wise step.

  • php artisan config:clear
  • php artisan cache:clear
  • composer dump-autoload
  • php artisan view:clear
  • php artisan route:clear
8 1

Laravel offers a tool to include dummy data to the database automatically. This process is called seeding. Developers can add simply testing data to their database table using the database seeder. It is extremely useful as testing with various data types allows developers to detect bugs and optimize performance. We have to run the artisan command make:seeder to generate a seeder, which will be placed in the directory database/seeds as like all others.

How to create database seeder

To generate a seeder, run the make:seeder Artisan command. All seeders generated by the laravel will be placed in the database/seeds directory:

php artisan make:seeder AdminTableSeeder

6 0

REPL is a type of interactive shell that takes in single user inputs, process them, and returns the result to the client.

The full form of REPL is Read—Eval—Print—Loop

1 0

With the help of update() function, we can update our data in the database according to the condition.

Example

                                                    

Blog::where(['id' => $id])->update([
   'title' => ’Best Interview Questions’,
   ‘content’ => ’Best Interview Questions’
]);

OR

DB::table("blogs")->where(['id' => $id])->update([
    'title' => ’Best Interview Questions’,
    ‘content’ => ’Best Interview Questions’
]);

6 2

Blog::where(['id' => 5])->orWhere([‘username’ => ‘info@bestinterviewquestion.com’])->update([
    'title' => ‘Best Interview Questions’,
]);

6 1

Laravel provides various methods that we can use in queries to get records with our conditions.

These methods are given below
  • where()
  • orWhere()
  • whereBetween()
  • orWhereBetween()
  • whereNotBetween()
  • orWhereNotBetween()
  • wherein()
  • whereNotIn()
  • orWhereIn()
  • orWhereNotIn()
  • whereNull()
  • whereNotNull()
  • orWhereNull()
  • orWhereNotNull()
  • whereDate()
  • whereMonth()
  • whereDay()
  • whereYear()
  • whereTime()
  • whereColumn()
  • orWhereColumn()
  • whereExists()
6 1

updateOrInsert() method is used to update an existing record in the database if matching the condition or create if no matching record exists.

Its return type is Boolean.

Syntax

DB::table(‘blogs’)->updateOrInsert([Conditons],[fields with value]);

Example

                                                    

DB::table(‘blogs’)->updateOrInsert(
     ['email' => 'info@bestinterviewquestion.com', 'title' => 'Best Interview Questions'],
     ['content' => 'Test Content']
);

10 0

To create migrations in Laravel, we have to use artisan command make:migration. The migration file will be stored in /database/migrations directory. As each migration file contains a timestamp, we can easily determine the order of migrations.

3 3

We can use hasTable() to check table exists in our database or not.

Syntax

Schema::hasTable('users'); // here users is the table name.

Example

                                                    

if(Schema::hasTable('users')) {
   // table is exists
} else {
   // table is not exists
}

4 0

if(Schema::hasColumn('admin', 'username')) ; //check whether admin table has username column
{
   // write your logic here
}

 

5 0

Inserts(): This method is used for insert records into the database table. No need the “id” should be autoincremented or not in the table.

Example

DB::table('bestinterviewquestion_users')->insert(
    ['title' => 'Best Interview Questions', 'email' => ‘info@bestinterviewquestion.com’]
);

It will return true or false.

 

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.

Example

$id = DB::table('bestinterviewquestion_users')->insert(
    ['title' => 'Best Interview Questions', 'email' => ‘info@bestinterviewquestion.com’]
);

6 0

With the user of Active Record in Laravel, our class directly maps into the present database table. It also fastens CRUD operations. Active Record is suitable for small projects and with big projects it can create various problems.

Syntax:

class User extends Eloquent {

}

2 2

Laravel accessors and mutators are customs, user-defined methods that allow you to format Eloquent attributes. Accessors are used to format attributes when you retrieve them from the database.

1. Defining an accessor

The syntax of an accessor is where getNameAttribute() Name is capitalized attribute you want to access.

public function getNameAttribute($value)
{
    return ucfirst($value);
}

 

2. Defining a mutator

Mutators format the attributes before saving them to the database.

The syntax of a mutator function is where setNameAttribute() Name is a camel-cased column you want to access. So, once again, let’s use our Name column, but this time we want to make a change before saving it to the database:

public function setNameAttribute($value)
{
    $this->attributes['name'] = ucfirst($value);
}

6 1

Please update 'default' => env('DB_CONNECTION', 'mysql'), in config/database.php. Update MySQL as a database whatever you want.

6 0

In Laravel, a closure is an anonymous function that often used as callback methods. Developers can also use it as a parameter in a function.

Example

                                                    

function handle(Closure $closure) {
    $closure();
}

handle(function(){
    echo ‘Best Interview Question’;
});

We can start by adding a Closure parameter to the handle method. This will be used as type hint us that the handle method takes a Closure.

We can call the handle method and pass a service as a parameter.

By using $closure(); in the handle method we tell Laravel to execute the given Closure which will then display ‘Best Interview Question.’

2 2

Simplified, an IoC container is a convenience Mechanism used to achieve Dependency Injection. This powerful tool manages class dependencies and has the power to resolve classes automatically without configuration.

An IoC Container is a convenience Mechanism for achieving Dependency Injection -Taylor Otwell

1 2

The latest version of Laravel is 6.0. It released on 3rd September 2019.

24 8

These are the most important concepts used in Laravel

  • Blade Templating
  • Routing
  • Eloquent ORM
  • Middleware
  • Artisan(Command-Line Interface)
  • Security
  • In built Packages
  • Caching
  • Service Providers
  • Facades
  • Service Container
12 3

If we want to get a table in Laravel application from a particular Model then we can use getTable() method.

Example

                                                    

$user = new BestInterviewQuestions;
$tableName = $user->getTable();
print_r($tableName);

0 0

Lumen is a newly introduced micro PHP framework which is a faster, smaller and leaner version of a full web application framework. It is introduced by Taylor Otwell, the creator of Laravel. It uses the same components as Laravel, but especially for microservices.

It has a simple installer like Laravel. You have to use this command to install lumen.
composer global require "laravel/lumen-installer=~1.0"

5 1

You can use an artisan command php artisan --version to know the laravel version.

1 0

We can do it with 3 simple steps.

  • Press Ctrl + Shift + ESC. Locate the php system walking artisan and kill it with proper click -> kill process.
  • Reopen the command-line and begin again the server.
  • Note that you ought to be able to kill the manner just by using sending it a kill sign with Ctrl + C.
0 0

Laravel uses "Blade Template Engine". It is a straightforward and powerful templating engine that is provided with Laravel.

9 1

You can use php artisan key:generate to generate your application key.

1 0

Here is an example to understand the concept of using group_concat() to join in Laravel. We have 3 tables like "dynamic_forms", "dynamic_forms_mapping", "categories".

Example

                                                    

$list = DB::table('dynamic_forms')
      ->select("dynamic_forms.*" ,DB::raw("(GROUP_CONCAT(wf_categories.name SEPARATOR ', ')) as category"))
      ->leftjoin("dynamic_forms_mapping", "dynamic_forms_mapping.form_id","=","dynamic_forms.id")
      ->leftjoin("categories", "dynamic_forms_mapping.category_id","=","categories.id")
      ->groupBy('dynamic_forms.id')
      ->where('dynamic_forms.status', 1)
      ->get();

0 0

You can extend the login expire time with config\session.php this file location. Just update lifetime the variables value. By default it is 'lifetime' => 120. According to your requirement update this variable.

Example

                                                    

'lifetime' => 180

2 0

It acts as a middleman between a request and a response. Middleware is a type of filtering mechanism used in Laravel application.

  • We can create middelware with
    php artisan make:middleware UsersMiddleware
  • Here "UsersMiddleware" is the name of Middleware. After this command a "UsersMiddleware.php" file created in app/Http/Middleware directory.
  • After that we have to register that middleware in kernel.php (available in app/Http directory) file in "$routeMiddleware" variable.
    'Users' => \App\Http\Middleware\UsersMiddleware::class,
  • Now we can call "Users" middleware where we need it like controller or route file.
  • We can use it in controller file like this.
    public function __construct() {
    $this->middleware('Users');
    }
  • In route file we can use like this.
    Route::group(['middleware' => 'Users'], function () {
    Route::get('/', 'HomeController@index');
    });
6 0
  • Offers a rich set of functionalities like Eloquent ORM, Template Engine, Artisan, Migration system for databases, etc
  • Libraries & Modular
  • It supports MVC Architecture
  • Unit Testing
  • Security
  • Website built in Laravel is more scalable and secure.
  • It includes namespaces and interfaces that help to organize all resources.
  • Provides a clean API.
3 0

Developers use packages to add functionality to Laravel. Packages can be almost anything, from great workability with dates like Carbon or an entire BDD testing framework such as Behat. There are standalone packages that work with any PHP frameworks, and other specially interned packages which can be only used with Laravel. Packages can include controllers, views, configuration, and routes that can optimally enhance a Laravel application.

There are many packages are available nowadays also laravel has some official packages that are given below:-
  • Cashier
  • Dusk
  • Envoy
  • Passport
  • Socialite
  • Scout
  • Telescope etc
2 1

Validation is a most important thing while designing an application. It validates the incoming data. It uses ValidatesRequests trait which provides a convenient method to authenticate incoming HTTP requests with powerful validation rules.

Here are some Available Validation Rules in Laravel are listed:-

  • Alpha
  • Image
  • Date Format
  • IP Address
  • URL
  • Numeric
  • Email
  • Size
  • Min , Max
  • Unique with database etc
3 0

With this @extends('layouts.master') we can extend this master layout in any view file.

In this example layouts are a folder that is placed in resources/views available and the master file will be there. Now "master.blade.php" is a layout file.

These laravel questions will help you to crack your future interviews.

4 0

We can use
return redirect('/')->withErrors('You can type your message here');
return redirect('/')->with('variableName', 'You can type your message here');
return redirect('/')->route('PutRouteNameHere');

3 0

Example

                                                    

<script type="text/javascript">

    $(document).ready(function() {

       $("FORMIDORCLASS").submit(function(e){

            // FORMIDORCLASS will your your form CLASS ot ID

            e.preventDefault();

       $.ajaxSetup({

            headers: {

                 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')

                // you have to pass in between tag

            }

    })

     var formData = $("FORMIDORCLASS").serialize();

    $.ajax({

          type: "POST",

         url: "",

         data : formData,

         success: function( response ) {

              // Write here your sucees message

         }, error: function(response) {

            // Write here your error message

         },

    });

    return false;

   });

});

</script>

4 0
request()->route()->getName()
3 0

$valiable1 = 'Best';

$valiable2 = 'Interview';

$valiable3 = 'Question';

return view('frontend.index', compact('valiable1', valiable2', valiable3'));

In you View File use can display by {{ $valiable1 }} or {{ $valiable2 }} or {{ $valiable3 }}

2 0

We have to pass protected $table = 'YOUR TABLE NAME'; in your respective Model

This is one of the most asked laravel interview questions.

Example

                                                    

namespace App;

use Illuminate\Database\Eloquent\Model;

class Login extends Model
{
    protected $table = 'admin';
    static function logout() {  
        if(session()->flush() || session()->regenerate()) {
            return true;
        }
    }
}

5 0

For this you have to get value & assign value in controller file in __construct() like this.

Example

                                                    

public function __construct() {       
        $this->middleware(function ($request, $next) {              
            $name = session()->get('businessinfo.name');  // get value from session
            View::share('user_name', $name);                   // set value for all View
            View::share('user_email', session()->get('businessinfo.email'));            
            return $next($request);
        });
}

1 0
Where Null Query

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

Where Not Null Query

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

4 0

ACL Stands for Access Control List.
If you needed to control get entry to certain sections of the site, or flip on or off unique portions of a web page for non-admins, or ensure any person can only edit their very own contacts, you wanted to deliver in a device like BeatSwitch Lock or hand-roll the functionality, which would be something referred to as ACL: Access Control Lists or basically the capability to outline a persons' capability to do and see certain matters primarily based on attributes of their person record.

3 1

Queues in Laravel are used by developers to create smooth application cycle by stacking complex tasks as jobs and dispatching these heavy jobs only with user permission or when it doesn’t disrupt the user experience.

You can visits here for more details : www.laravel.com

2 1

We can add multiple AND operator at in a single where() conditions as well as we can also add seprate where() for particular AND condition.

Example

                                                    
DB::table('client')->where('status', '=', 1)->where('name', '=', 'bestinterviewquestion.com')->get();

DB::table('client')->where(['status' => 1, 'name' => 'bestinterviewquestion.com'])->get();

3 1
Laravel supports various joins that's are given below:-
  • Inner Join

    DB::table('admin') ->join('contacts', 'admin.id', '=', 'contacts.user_id') ->join('orders', 'admin.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price') ->get();

  • Left Join / Right Join

    $users = DB::table('admin') ->leftJoin('posts', 'admin.id', '=', 'posts.admin_id') ->get();
    $users = DB::table('admin') ->rightJoin('posts', 'admin.id', '=', 'posts.admin_id') ->get();

  • Cross Join

    $user = DB::table('sizes') ->crossJoin('colours') ->get();

  • Advanced Join

    DB::table('admin') ->join('contacts', function ($join) { $join->on('admin.id', '=', 'contacts.admin_id')->orOn(...); }) ->get();

  • Sub-Query Joins

    $admin = DB::table('admin') ->joinSub($latestPosts, 'latest_posts', function ($join) { $join->on('admin.id', '=', 'latest_posts.admin_id'); })->get();

5 0

request()->route()->getActionMethod()

5 1

Blade is very simple and powerful templating engine that is provided with Laravel. Laravel uses "Blade Template Engine".

7 3

It is an array which contains all those fields of table which can be create directly new record in your Database table.

Example

                                                    

class User extends Model {
        protected $fillable = ['username', 'password', 'phone'];
}

4 1

It is the reverse of fillable. When a guarded specifies which fields are not mass assignable.

Related Article: PHP interview questions

Example

                                                    

class User extends Model {
     protected $guarded = ['user_type'];
}

 

4 0

Example

                                                    

use Illuminate\Support\Facades\Auth;

$userinfo = Auth::user();

print_r($userinfo );

6 1

Yes, It supports caching like Memcached and Redis. By default, laravel is configured with file cache which is stores the serialized, cached objects in the files. Normally we can use Memcached or Redis for large projects.

6 0

A Traits are a technique for code reuse in single inheritance languages.

Example

                                                    

I Created a Traits directory in my Http directory named BrandTrait.php


use App\Http\Traits\BrandTrait;
class YourController extends Controller {
    use BrandTrait;
    public function addProduct() {
       //$brands = Brand::all();
       // $brands = $this->BrandTrait(); // this is wrong
       $brands = $this->brandsAll();
    }
}

Here is my BrandTrait.php

namespace App\Http\Traits;
use App\Brand;
trait BrandTrait {
    public function brandsAll() {
        // Get all the brands from the Brands model or table.
        $brands = Brand::all();
        return $brands;
    }
}

 

2 2

You can use the following syntax to check ajax request in laravel.
if ($request->ajax()) {
     // Now you can write your code here.
}

5 0

To check the email value is sent or not in request, you can use $request->has('email')

Example

                                                    

if($request->has('email')) {
     // email value is sent from request
} else {
    // email value not sent from request
}

2 0

Laravel includes a number of global "helper" string and array functions. These are given below:-

Laravel Array Helper functions
  • Arr::add()
  • Arr::has()
  • Arr::last()
  • Arr::only()
  • Arr::pluck()
  • Arr::prepend() etc
Laravel String Helper functions
  • Str::after()
  • Str::before()
  • Str::camel()
  • Str::contains()
  • Str::endsWith()
  • Str::containsAll() etc
3 1

You can cut out a route from CSRF verification by using adding the route to $except property at VerifyCsrfToken middleware.

Example

                                                    

 

protected $except = [
     'admin/*/edit/*'
];

2 2

Review

No Image
Deepak Chaudhary
1 month ago
5

Thank you so much, this is really helpful interview questions and answers

No Image
Riya
1 month ago
4.5

Such a great Questions and Answers

No Image
rekha
1 month ago
4

Really good questions and answers

No Image
padar roy
3 weeks ago
5

A lot of thanks

No Image
partho
3 weeks ago
5

nice

No Image
B Anil Kumar
2 weeks ago
5

Thanks for this Information

No Image
Satyam Vishwakarma
1 week ago
5

Thank you for providing this are questions very helpful for me

Add Review

Ask Question