Laravel Interview Questions | Eklavya Online

Laravel Interview Questions

Laravel’s Query Builder provides more direct access to the database, alternative to the Eloquent ORM. It doesn’t require SQL queries to be written directly. Instead, it offers a set of classes and methods which are capable of building queries programmatically. It also allows specific caching of the results of the executed queries.

  • PHP Version>=7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension

PHP artisan is a command-line interface/tool provided with Laravel. It consists of several useful commands which can be helpful while building an application. There are few artisan commands given below:

PHP artisan list

A ‘list’ command is used to view a list of all available Artisan commands.

PHP artisan help

Every command also contains a ‘help’ screen, which is used to display and describe the command’s available arguments and options. To display a help screen, run ‘help’ command.

PHP artisan tinker

Laravel’s artisan tinker is a repl (Read-Eval-Print Loop). Using tinker, one can write actual PHP code through command-line. One can even update or delete table records in the database.

PHP artisan -version

By using this command, one can view the current version of Laravel installation.

PHP artisan make model model_name

This command creates a model ‘model_name.php’ under the ‘app’ directory.

PHP artisan make controller controller_name

This command is used to build a new controller file in app/Http/Controllers folder.

ORM stands for Object-Relational Mapping. It is a programming technique which is used to convert data between incompatible type systems in object-oriented programming languages.

Yes, Laravel provides support for popular caching backends like Memcached and Redis.

By default, Laravel is configured to use file cache driver, which is used to store the serialized or cached objects in the file system. For huge projects, it is suggested to use Memcached or Redis.

Laravel’s Contracts are the set of interfaces which are responsible for defining the core functionality of services provided by the Laravel framework.

User() function is used to get the logged-in user

Example

if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}

CSRF protection stands for Cross-Site Request Forgery protection. CSRF detects unauthorized attacks on web applications by the unauthorized users of a system. The built-in CSRF plug-in is used to create CSRF tokens so that it can verify all the operations and requests sent by an active authenticated user.

To turn off CSRF protection for a specific route, we can add that specific URL or Route in $except variable which is present in the app\Http\Middleware\VerifyCsrfToken.phpfile.

Example

classVerifyCsrfToken extends BaseVerifier
{
protected $except = [
‘Pass here your URL’,
];
}

There are some official packages provided by Laravel which are given below:

Cashier

Laravel cashier implements an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services. It controls almost all of the boilerplate subscription billing code you are dreading writing. Moreover, the cashier can also control coupons, subscription quantities, swapping subscription, cancellation grace periods, and even generate invoice PDFs.

Envoy

Laravel Envoy is responsible for providing a clean, minimal syntax for defining frequent tasks that we run on our remote servers. Using Blade style syntax, one can quickly arrange tasks for deployment, Artisan commands, and more. Envoy only provides support for Mac and Linux.

Passport

Laravel is used to create API authentication to act as a breeze with the help of Laravel passport. It further provides a full Oauth2 server implementation for Laravel application in a matter of minutes. Passport is usually assembled on top of League OAuth2 server which is maintained by Alex Bilbie.

Scout

Laravel Scout is used for providing a simple, driver-based solution for adding full-text search to the eloquent models. Using model observers, Scout automatically keeps search indexes in sync with eloquent records.

Socialite

Laravel Socialite is used for providing an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, and Linkedln, etc. It controls almost all the boilerplate social authentication code that you are dreading writing.

Controllers are kept in app/http/Controllers directory.

Some of the methods that Query Builder provides are:

  • count()
  • max()
  • min()
  • avg()
  • sum()

An event is an activity or occurrence recognized and handled by the program. Events in Laravel provide simple observer implementations which allow us to subscribe and listen for events within our application. The event classes are stored in app/Events, while their listeners are stored in app/Listeners of our application. These can be generated using Artisan console commands. A single event may contain multiple listeners that do not depend on each other.

There are some events examples in Laravel which are:

  • A new user is registered.
  • A new comment is posted.
  • User login/logout.
  • A new product is added.

We can implement a package in Laravel by:

  • Creating a package folder and name it.
  • Creating Composer.json file for the package.
  • Loading package through main composer.json and PSR-4.
  • Creating a Service Provider.
  • Creating a Controller for the package.
  • Creating a Routes.php file.

The syntax to clear cache in Laravel is given below:

  • php artisan cache: clear
  • php artisan config: clear
  • php artisan cache: clear

Homestead is an official, pre-packaged, vagrant virtual machine which provides Laravel developers all the necessary tools to develop Laravel out of the box. It also includes Ubuntu, Gulp, Bower, and other development tools which are useful in developing full-scale web applications. It provides a development environment which can be used without the additional need to install PHP, a web server, or any other server software on the machine.

In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using mass-assignment.

Mass assignment refers to sending an array to the model to directly create a new record in Database.

Code Source

class User extends Model {
protected $fillable = [‘name’, ’email’, ‘mobile’];
// All fields inside $fillable array can be mass-assigned
}

Unit testing is built-in testing provided as an integral part of Laravel. It consists of unit tests which detect and prevent regressions in the framework. Unit tests can be run through the available artisan command-line utility.

PHP compact function receives each key and tries to search a variable with that same name. If a variable is found, then it builds an associate array.

All Laravel routes are defined in route files, which are stored in the routes directory. These files are loaded by the MVC framework. The routes/web.php files define routes that are available for the web interface. Those routes are allotted as the web middleware group, which provide features such as session state and CSRF protection. The routes available in routes/api.php are stateless and are allotted as the API middleware group. For most of the applications, one should start by defining routes in routes/web.php file.

Validations are approaches that Laravel use to validate the incoming data within the application.

They are the handy way to ensure that data is in a clean and expected format before it gets entered into the database. Laravel consists of several different ways to validate the incoming data of the application. By default, the base controller class of Laravel uses a ValidatesRequests trait to validate all the incoming HTTP requests with the help of powerful validation rules.

PHP Traits is a group of methods which can be included within another class. A Trait cannot be instantiated by itself like an abstract class. Traits are generated to reduce the limitations of single inheritance in PHP. It allows a developer to reuse sets of methods freely in various independent classes living in different class hierarchies.

Example

trait Sharable {
public function share($item)
{
return ‘share this item’;
}
}
We can then include this Trait within other classes like:

class Post {
use Sharable;
}
class Comment {
use Sharable;
}
Now, if we want to create new objects out of these classes, we would find that they both have the share() method available:

$post = new Post;
echo $post->share(”); // ‘share this item’
$comment = new Comment;
echo $comment->share(”); // ‘share this item’

As the name suggests, middleware works as a middleman between request and response. Middleware is a form of HTTP requests filtering mechanism. For example, Laravel consists of middleware which verifies whether the user of the application is authenticated or not. If a user is authenticated and trying to access the dashboard then, the middleware will redirect that user to home page; otherwise, a user will be redirected to the login page.

There are two types of middleware available in Laravel:

Global Middleware

It will run on every HTTP request of the application.

Route Middleware

It will be assigned to a specific route.

Syntax

php artisan make:middlewareMiddelwareName
Example

php artisan make:middlewareUserMiddleware

We can get the user’s IP address using:

public function getUserIp(Request $request){
// Gettingip address of remote user
return $user_ip_address=$request->ip();
}

The guarded attribute is the opposite of fillable attributes.

In Laravel, fillable attributes are used to specify those fields which are to be mass assigned. Guarded attributes are used to specify those fields which are not mass assignable.

Code Source

class User extends Model {
protected $guarded = [‘role’];
// All fields inside the $guarded array are not mass-assignable
}
If we want to block all the fields from being mass-assigned, we can use:

protected $guarded = [‘*’];
$fillable serves as a “white list” whereas $guarded functions serves like a “black list”. One should use either $fillable or $guarded.

Laravel is free to use, open-source web framework based on PHP. It is developed by Taylor Otwell . It supports the MVC (Model-View-Controller) architectural pattern. Laravel provides an expressive and elegant syntax, which is useful for creating a wonderful web application easily and quickly. The first version of Laravel was released on 9th June 2011 .

As of SitePoint survey in March 2015Laravel was voted as one of the most popular PHP frameworks along with Symfony, Nette, CodeIgniter, and Yii2 .

In Laravel, a Closure is an anonymous method which can be used as a callback function. It can also be used as a parameter in a function. It is possible to pass parameters into a Closure. It can be done by changing the Closure function call in the handle() method to provide parameters to it. A Closure can access the variables outside the scope of the variable.

Example

function handle(Closure $closure) {
$closure();
}
handle(function(){
echo ‘Interview Question’;
});
It is started by adding a Closure parameter to the handle() method. 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 the ‘Interview Question.’

Laravel Facades provide static-like interface classes which are available in the application’s service container. Laravel self-ships with several available facades, gives access to almost all features of Laravel. Facades also help to access a service directly from the container itself. It is described in the Illuminate\Support\Facades namespace. Hence, it is easy to use.

Example

use Illuminate\Support\Facades\Cache;
Route::get(‘/cache’, function () {
return Cache::get(‘PutkeyNameHere’);
})

The major differences between Laravel 4 and Laravel 5.x are given below:

  • The old app/models directory is entirely removed.
  • Controllers, middleware, and requests (a new class in Laravel 5.0) are now combined under the app/Http directory.
  • A new app/Providers directory changes the app/start files from previous versions of Laravel of 4.x.
  • Application language files and views are moved to the resources directory.
  • All major Laravel components include interfaces that are located in the illuminate/contracts repository.
  • Laravel 5.x now supports HTTP middleware. The included authentication and CSRF “filters” are converted to middleware.
  • One can now type-hint dependencies on controller methods.
  • User authentication, registration, and password reset controllers are now combined out of the box, including simple related views which are located at resources/views/auth.
  • One can now define events as objects instead of simply using strings.
  • Laravel 5 also allows us to represent our queued jobs as simple command objects in addition to the queue job format, which was supported in Laravel 4. These commands are available inside the app/Commands display.

Reverse routing in Laravel is used to generate the URL based on name or symbol. It defines a relationship between the links and, Laravel routes, and it is possible to make later changes to the routes to be automatically propagated into relevant links. When the links are generated using names of existing routes, the appropriate uniform resource identifiers (URIs) are automatically generated by Laravel. Reverse routing provides flexibility to the application and helps the developer to write cleaner codes.

Route Declaration:

Route::get(‘login’, ‘users@login’);
A link can be created to it using reverse routing, which can be further transferred in any parameter that we have defined. If optional parameters are not supplied, they are removed automatically from the generated links.

{{ HTML::link_to_action(‘users@login’) }}
By using it, a URL like https://abc.go.com/loginwill be created automatically.

Lumen is a PHP micro-framework built on Laravel’s top components. It is created by Taylor Otwell (creator of Laravel). It is created for building Laravel based micro-services and blazing fast APIs. It is one of the fastest micro-frameworks available. Lumen is not a complete web framework like Laravel and used for creating APIs only. Therefore, most of the components, such as HTTP sessions, cookies, and templating, are excluded from Lumen. Lumen provides support for features such as logging, routing, caching queues, validation, error handling, middleware, dependency injection, controllers, blade templating, command scheduler, database abstraction, the service container, and Eloquent ORM, etc.

One can install Lumen using composer by running the command given below:

composer create-project –prefer-distlaravel/lumen blog

Laravel is configured to use MySQL by default.

To change its default database type, edit the file config/database.php:

  • Search for ‘default’ =>env(‘DB_CONNECTION’, ‘mysql’)
  • Change it to whatever required like ‘default’ =>env(‘DB_CONNECTION’, ‘sqlite’)
    By using it, MySQL changes to SQLite.

Migrations can be defined as version control for the database, which allows us to modify and share the application’s database schema easily. Migrations are commonly paired with Laravel’s schema builder to build the application’s database schema easily.

A migration file includes two methods, up() and down(). A method up() is used to add new tables, columns or indexes database and the down() method is used to reverse the operations performed by the up() method.

We can generate a migration and its file by using the make:migration.

Syntax

php artisan make:migration blog
By using it, a current date blog.php file will be created in database/migrations

We can easily use custom table in Laravel by overriding protected $table property of Eloquent. Here, is the sample:

class User extends Eloquent{
protected $table=”my_user_table”;
}

Some of the main features of Laravel are:

  • Eloquent ORM
  • Query builder
  • Reverse Routing
  • Restful Controllers
  • Migrations
  • Database Seeding
  • Unit Testing
  • Homestead

One can easily check the current version of Laravel installation using the -version option of artisan command.

Php artisan -version

There are few benefits of Laravel which can be considered over other PHP frameworks:

  • In Laravel, Setup and customization process is fast and easy as compared to others.
  • Laravel supports multiple file systems.
  • It has pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel Passport, Laravel elixir, and Laravel Scout, etc.
  • It consists of in-built Authentication System.
  • It supports Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
  • “Artisan” command-line tool for creating a database structure, code skeleton, and build their migration.

In Laravel, Bundles are also known as Packages. Packages are the primary way to add more functionality to Laravel. Packages can be anything, from a great way to work with dates like Carbon, or an entire BDD testing framework like Behat. Laravel also provides support for creating custom packages.

There are different types of packages. Some of them are stand-alone packages. This means they can work with any PHP framework. The frameworks like Carbon and Behat are examples of stand-alone packages. Other packages are intended for use with Laravel. These packages may contain routes, controllers, views, and configurations which are mainly designed to enhance a Laravel application.

The blade is a simple but powerful templating engine provided with Laravel. There is no restriction to use PHP codes in the views. All the blade views are compiled into simple PHP code and cached until they are modified. Blade adds effectively zero overhead to our application. Blade view files in Laravel use the .blade.phpfile extension and are saved in the resources/views directory.

When an application is in maintenance mode, a custom view is displayed for all requests into the application. It makes it easy to “disable” application while it is updating or performing maintenance. A maintenance mode check is added in the default middleware stack for our application. When an application is in maintenance mode, a MaintenanceModeException will be thrown with a status code of 503.

We can enable or disable maintenance mode in Laravel 5, simply by executing the below command:

// Enable maintenance mode
php artisan down

// Disable maintenance mode
php artisan up

Service providers can be defined as the central place to configure all the entire Laravel applications. Applications, as well as Laravel’s core services, are bootstrapped via service providers. These are powerful tools for maintaining class dependencies and performing dependency injection. Service providers also instruct Laravel to bind various components into the Laravel’s Service Container.

An artisan command is given here which can be used to generate a service provider:

php artisan make: provider ClientsServiceProvider
Almost, all the service providers extend the Illuminate\Support\ServiceProviderclass. Most of the service providers contain below-listed functions in its file:

Register() Function
Boot() Function
Within the Register() method, one should only bind things into the service container. One should never attempt to register any event listeners, routes, or any other piece of functionality within the Register() method.

The cursor method allows us to iterate through our database using a cursor, which will only execute a single query. While processing large amounts of data, the cursor method may be used to reduce your memory usage greatly.

Example

foreach (Product::where(‘name’, ‘bar’)->cursor() as $flight) {
//make some stuff
}

Eloquent ORM (Object-Relational Mapping) is one of the main features of the Laravel framework. It may be defined as an advanced PHP implementation of the active record pattern.

Active record pattern is an architectural pattern which is found in software. It is responsible for keeping in-memory object data in relational databases

Eloquent ORM is also responsible for providing the internal methods at the same time when enforcing constraints on the relationship between database objects. Eloquent ORM represents database tables as classes, with their object instances tied to single table rows, while following the active record pattern.

We can create a helper file using composer as per the given below steps:

Make a file “app/helpers.php” within the app folder.

Add

“files”: [
“app/helpers.php”
]
in the “autoload” variable.

Now update composer.json with composer dump-autoload or composer update.

dd stands for “Dump and Die.” Laravel’s dd() function can be defined as a helper function, which is used to dump a variable’s contents to the browser and prevent the further script execution.

Example

dd($array);

Below are the types of relationships that Laravel Eloquent ORM supports:

  • One to One
  • One to Many
  • One to Many (Inverse)
  • Many to Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations

A composer is a dependency manager in PHP. It manages the dependencies which are required for a project. It means that the composer will pull in all the necessary libraries, dependencies, and manage all at a single place.

Laravel Installation Steps:

If you don’t have a composer on a system, download composer from https://getcomposer.org/download/
Open command prompt
Go to htdocs folder
Run the below command under C:\xampp\htdocs>

Service container in Laravel is one of the most powerful features. It is an important, powerful tool for resolving class dependencies and performing dependency injection in Laravel. It is also known as IoC container.

Dependency injection is a term which essentially means that class dependencies are “injected” into the class by the constructor or, in some cases,” setter” methods.

Advantages of Service Container

  • It can handle class dependencies on object creation.
  • It can combine interfaces to concrete classes.

We need to create a new model instance if we want to create a new record in the database using Laravel eloquent. Then we are required to set attributes on the model and call the save() method.

Example

public functionsaveProduct(Request $request )
$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();

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

Example

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

  • PHP Version>=7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension