Loading…
Laravel Interview Questions

What is Laravel?

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.

About Laravel
What is Laravel Laravel is a free and open-source PHP framework that follows the model–view–controller design (MVC) pattern.
Latest Version 5.8, released on 26th February 2019
Created By Taylor Otwell
Laravel Follows MVC architectural pattern
Written in PHP 7
Laravel Licence MIT License
Official Website https://laravel.com/

We have a collection of logical & advanced laravel interview questions that helps to crack your interviews.

Development History

Laravel was created by Taylor Otwell. Laravel's first beta version was released in June 2011. Laravel 2 was released in September 2011. Laravel 3 was released in February 2012. Laravel 4 was released in May 2013. Majority of candidates are asked this information in Laravel Interview Questions. Laravel 5 was released in February 2015.

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 current version is 5.8

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

Advantages of Laravel

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

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.

Laravel Interview Questions and answers

Looking for a new job? Do not miss to read our Laravel Interview Questions and answers. Whether you are a fresher or an experienced, these questions and answers that can help you to crack your interview.

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

 

We have a blog related How to install Laravel by Composer Step by Step. You can read it

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.

This information is critical for Laravel Advanced Interview Questions.

In Laravel middleware acts as a middleman between request and response. Middleware is a type of HTTP requests filtering mechanism.
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

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

Service providers is a central place of all entire Laravel application. A service provider is a powerful tool for managing class dependencies and performing dependency injection. Service provider tells Laravel to bind various components into the laravel's service container.

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

We can use whereBetween() method to get data between two dates with Query.

Example

                                                    

Blog::whereBetween('created_at', [$date1, $date2])->get();

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',
      ];
}

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

The facade is a type of class which provides a static interface to services. Facade helps to access a service directly from the container. It is defined in the Illuminate\Support\Facades namespace. So that we can use it easily.

Example

                                                    

use Illuminate\Support\Facades\Cache;

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

     return Cache::get('PutkeyNameHere');

});

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

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
  • PHP version >= 7.1.3
  • PDO PHP Extension should allow.
  • OpenSSL PHP Extension should allow.
  • XML PHP Extension should allow.
  • AllowBCMath PHP Extension.
  • Allow Tokenizer PHP Extension.
  • Mbstring PHP Extension should allow.
  • Ctype PHP Extension should allow.
  • JSON PHP Extension should allow.

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.;
  • 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]);
    }

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

This is one of the frequently asked Laravel interview questions.

Service Container is a powerful tool which is used for managing class dependencies and performing dependency injection. It is also known as the IoC container.

Advantages of Service Container
  • Capacity to manage class dependencies on object creation.
  • Service Container as a Registry.
  • Binding of interfaces to concrete classes.

Point to be noted: Go through this Q&A very thoroughly as this is one of the important Laravel interview questions?

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

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’]);

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

1. For set cookie Value we have to use Cookie::put('key', 'value');

2. For get cookie Value we have to use Cookie::get('key');

3. For remove cookie Value we have to use Cookie::forget('key')

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

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.

 

You can create a constants.php page/file 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');

There are vast differences between laravel 4 and laravel 5 regarding LTS, features, file structures, etc.

Laravel 4 was the one who brought significant popularity to the Laravel framework, but this version not updated anymore, and it also lacks a lot of functions released in Laravel 5.

  • Laravel 4 released May 2013 but Laravel 5 released in February 2015.
  • Laravel 5 has LTS Supports. It means the LTS version stands for Long Term Support. It implies that bugfixes for that version will be provided for two years, until the next LTS version.
  • In Laravel 5, Controllers, middleware, and requests are now grouped under the app/Http directory.
  • A new directory app/Providers replaces the app/start files from previous versions of Laravel 4.x.
  • In Laravel 5 Application language files and views have been moved to the resources directory.
  • New Artisan command route: cache to drastically speed up the registration of your ways.
  • Laravel 5 supported HTTP middleware and included authentication and CSRF "filters" have been converted to middleware but not in Laravel 4.
  • Now in Laravel 5, User registration, password reset and authentication controllers are included out of the box, as well as simple corresponding views, which are located at in resources/views/auth.
  • Laravel 5 gives a Socialite package which is an optional, Laravel 5.0+ compatible package that provides painless authentication with OAuth providers.
  • The favorite dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.

In contrast to Laravel 4 to 5 version differences, which is huge, 5.x and 5.y versions are not that different. Some functions added, some updated/removed in laravel 5, but the core structure remains the same.

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.

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;

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

Our first step should be

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

After our query it should be placed

$querieslog = DB::getQueryLog();

After that it shou;ld be placed

dd($querieslog)

A lot of recent Laravel interview questions were based on this information.

Example

                                                    

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

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

$log = DB::getQueryLog();

dd($log);

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

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.

An ORM stands for object-relational mapper. It is essential features provided by Laravel Framework. Laravel allows us to work with database objects and relationships using an eloquent. Each table has a particular Model which are used to interact with that table in laravel application.

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

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

Dependency injection is a technique that essentially means this: class dependencies are "injected" into the class via the constructor, or it’s "setter" methods. 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.

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>

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

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

It is a unified API across a variety of different queue back-ends. It allows you to defer the processing of a time-consuming task, such as sending an e-mail, until a later time which drastically speeds up web requests to your application.

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

 

This is another laravel interview questions. Answer this one as an excellent basis.

 

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

Laravel provides a tool to add dummy data to our databases automatically that call it seeding.

With the help of database seeder, we can add simply testing data on our database table. Database seed is beneficial because testing with various data allows you to detect bugs you otherwise would have overlooked likely. We have to make one-time seeder with some dummy data directly; that way we can reuse when you deploy the project first time. We can make seeder after migration of the table.

All classes in the seed are placed in the directory database/seeds

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

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’
]);

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

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()

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

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
}

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

 

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’]
);

In Active Record our class directly maps to the database table. withIn Laravel 5 CRUD operations using the Active Record pattern is extremely fast. Laravel provides a feature to choose another table name but yet you’re still mapping it directly to the database table.

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

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

In Laravel, A Closure is an anonymous method and used as callback functions and also can be used as a parameter in a process. It is possible to pass parameters into a Closure. We can do by changing the Closure function call in the handle method to give on a parameter.

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

IoC container is a powerful tool which is used to manage class dependencies in Laravel. It has the power to resolve classes without configuration automatically.

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

The current version is 5.8. It released on February 26th, 2019.

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

It is the perfect solution for developing Laravel based microservices and fast APIs. It is a new project that is created by Taylor Otwell. It is built for microservices, not so much for user interfacing applications.

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

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

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');
    });
  • 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.

Laravel Packages are a primary way of adding functionality to Laravel. Packages may have separate routes, controllers, views, and configuration specifically intended to enhance the 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

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

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

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

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

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>

request()->route()->getName()

$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 }}

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;
        }
    }
}

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

It provide simpe API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database. It also allow us to defer the processing of a time consuming task, such as sending an email. These time consuming tasks helps to speeds up web requests to our application.

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

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

Example

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

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

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

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'];
}

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

Example

                                                    

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

Example

                                                    

use Illuminate\Support\Facades\Auth;

$userinfo = Auth::user();

print_r($userinfo );

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.

Ask Question