Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

251.

What is Queues?

Answer»

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.

252.

What is ACL in laravel?

Answer»

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.

253.

How to use Where null and Where not null eloquent query in Laravel?

Answer»

Where NULL Query

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

Where Not Null Query

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

254.

How to create custom validation rules with Laravel?

Answer»
  • 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 &AMP;& $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]);
    }
255.

How to override a Laravel model's default table name?

Answer»

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

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

256.

How to pass multiple variables by controller to blade file?

Answer»

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

257.

How to get current route name?

Answer»

request()->route()->GETNAME()

92. How to create MODEL controller and migration in a single ARTISAN COMMAND in Laravel?

php artisan make:model ModelNameEnter -mcr

258.

How to use Ajax in any form submission?

Answer» 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>

259.

How to redirect form controller to view file in laravel?

Answer»

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

260.

How to extend a layout file in laravel view?

Answer»

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.

261.

Is laravel good for API?

Answer»

Laravel is an appropriate choice for PHP builders to use for building an API, especially when a project’s necessities are not exactly defined. It's a comprehensive framework suitable for any type of application DEVELOPMENT, is logically structured, and ENJOYS robust COMMUNITY support.

Laravel includes FACTORS for not solely API development, but front-end templating and singe-page software WORK, and other aspects that are totally unrelated to only building a net utility that responds to REST Http calls with JSON.

262.

What is validation in laravel and how it is used?

Answer»

Validation is the 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
263.

What is forge in Laravel?

Answer»

FORGE in Laravel is ONE tool that is USED for deploying as well as configuring numerous WEB applications. This was created by the developers of the renowned Laravel framework, though this can be utilized for automating the deployment-related to any of the web application on the condition that these applications use the PHP server. Forge in Laravel automates each and every necessary installation as well as configuration step, which enables users to get their website up along with running quickly.

264.

What is Package in laravel? Name some laravel packages?

Answer»

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

How to rollback last migration in laravel?

Answer»

You can USE PHP ARTISAN MIGRATE:ROLLBACK --step=1.

266.

What are the features of laravel?

Answer»
  • 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.
82. What are gates in laravel?

Laravel Gate holds a sophisticated mechanism that ensures the users that they are authorized for performing ACTIONS on the resources. The implementation of the models is not defined by Gate. This renders the users the freedom of writing each and every complex spec of the use CASE that a user has in any way he/she wishes. Moreover, the ACL packages can be used as well with the Laravel Gate. With the help of Gate, users are able to decouple access logic and BUSINESS logic. This way clutter can be removed from the controllers.

267.

What is Implicit Controller in Laravel?

Answer»

It allows us to easily define a single route to handle all activities in a CONTROLLER. We can define the route USING the Route::controller METHOD:

268.

What is PHP artisan in laravel? Name some common artisan commands?

Answer»

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

How to use GROUP_CONCAT() with JOIN in Laravel?

Answer»

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

270.

How to generate application key in laravel?

Answer»

You can use php artisan KEY:GENERATE to generate your APPLICATION key.

271.

How do I stop Artisan serve in Laravel?

Answer»

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

How to know laravel version?

Answer»

You can use an artisan COMMAND PHP artisan --VERSION to know the laravel version.

273.

How to upgrade form laravel 5 to laravel 6?

Answer»
  • Open the laravel project inside the code editor.
  • Go to the Composer.json file and change the laravel/framework from 5 to 6.
  • Open the terminal and write the COMMAND – composer update and hit ENTER to wait for the update to complete.
  • After finished RUN the server command (PHP artisan serve) and run the project in a browser.
  • After this , again go to terminal and write command –(composer require laravel/ui) and hit enter and download the packages.
  • Then, for creating the auth file write the command ( PHP artisan ui vue-auth) to make the auth file in laravel 6.0.

In this way, we can upgrade from laravel 5 to laravel 6.

274.

What is lumen?

Answer»

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"

275.

What is eager loading in Laravel?

Answer»

Eager LOADING is used when we have to fetch some USEFUL data along with the data which we want from the DATABASE. We can eager LOAD in LARAVEL using the load() and with() commands.

276.

What are the basic concepts in laravel?

Answer»

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

How to change your default database type in Laravel?

Answer»

Please UPDATE 'default' => ENV('DB_CONNECTION', 'mysql'), in config/database.php. Update MySQL as a database whatever you WANT.

278.

What is the use of Accessors and Mutators?

Answer»

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

279.

What are the difference between insert() and insertGetId() in laravel?

Answer»

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' => ‘[email protected]’]
);

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' => ‘[email protected]’]
);

280.

How to check column is exists or not in a table using Laravel?

Answer»

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

281.

How to check table is exists or not in our database using Laravel?

Answer»

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
}

282.

How to use updateOrInsert() method in Laravel Query?

Answer»

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([CONDITIONS],[fields with value]);

Example

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

283.

How to use multiple OR condition in Laravel Query?

Answer»

Blog::where(['id' => 5])->orWhere([‘username’ => ‘[email PROTECTED]’])->update([
    'title' => ‘BEST Interview QUESTIONS’,
]);

64. Please write some additional where Clauses in Laravel?

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

How to use update query in Laravel?

Answer»

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

285.

What is a REPL?

Answer»

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

286.

What is seed in laravel?

Answer»

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

287.

How to clear cache in Laravel?

Answer»

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

What is tinker in laravel?

Answer»

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.

289.

What are the advantages of Queue?

Answer»
  • 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.
290.

What is faker in Laravel?

Answer»

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.

291.

What are views?

Answer»

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 &LT;html&GT;     <BODY>        <h1>Best Interview Question<h1>     </body> </html>
292.

How do you call Middleware in laravel?

Answer»

In LARAVEL, we can call MULTIPLE Middlewares in Controller FILE and route file.

1. In Controller file, you can call LIKE this.

public function __construct() {
   $this->middleware(['revalidateBackHistory', 'validateUser']);
}

2. In route file, you can call multiple middleware like this.

Route::get('/', function () {
  //
})->middleware(['firstMiddle', 'secondMiddle']);

293.

How to run job queue through command line in laravel?

Answer»

You can run this ARTISAN Command php artisan QUEUE:work --tries=3 OR --once --queue=JobQueueName

You can use both --tries or --once. When you will use --once then you command will execute singly and when you will use --tries=2 the it will execute TWO TIMES and further.

294.

What is the use of the cursor() method in Laravel?

Answer»

The ELOQUENT CURSOR () method allows a USER to iterate through the database records USING a cursor, which will execute only a single query. This method is quite useful when processing large amounts of data to significantly reduce MEMORY usage.

295.

How do you run test cases in laravel?

Answer»

To RUN test cases in Laravel, you should use the PHPUnit or artisan test command.

Example

namespace Tests\Unit;
use PHPUnit\Framework\TESTCASE;
CLASS ExampleTest extends TestCase
{
     * @return void
    PUBLIC FUNCTION testBasicTest()
    {
        $this->assertTrue(true);
    }
}

296.

How to rollback a particular migration in laravel?

Answer»

If you want to ROLLBACK a specific migration, LOOK in your migrations table, you’ll see each migration table has its own batch number. So, when you roll BACK, each migration that was part of the last batch gets rolled back.

Use this command to rollback the last batch of migration

php ARTISAN migrate:rollback --step=1

Now, suppose you only want to roll back the very last migration, just increment the batch number by one. Then next TIME you run the rollback command, it’ll only roll back that one migration as it is a batch of its own.

297.

What is Singleton design pattern in laravel?

Answer»

The Singleton Design PATTERN in LARAVEL is one where a CLASS presents a single instance of itself. It is used to restrict the instantiation of a class to a single object. This is useful when only one instance is required across the system. When used properly, the first call SHALL instantiate the object and after that, all calls shall be returned to the same instantiated object.

298.

What is Vapor in Laravel?

Answer»

Vapor in LARAVEL is a SERVERLESS DEPLOYMENT platform auto-scaling and POWERED by AWS Lambda. It used to manage Laravel Infrastructure with the scalability and simplicity of serverless.

299.

What is Repository pattern in laravel?

Answer»

It allows using OBJECTS without having to know how these objects are persisted. It is an abstraction of the data layer. It means that our business logic no need to know how data is retrieved. The business logic RELIES on the REPOSITORY to get the CORRECT data.

Basically it is used to decouple the data access LAYERS and business logic in our application.

300.

How to use skip() and take() in Laravel Query?

Answer»

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