Laravel Interview Questions – Set 02

What do you know about Traits in Laravel?

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’

How will you explain middleware in Laravel?

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

How can we get the user’s IP address in Laravel?

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

How will you explain Guarded Attribute in a Laravel model?

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.

What is Laravel?

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 .

What do you know about Closures in Laravel?

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

What do you know about Facades in Laravel? Explain.

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 IlluminateSupportFacades namespace. Hence, it is easy to use.

Example

use IlluminateSupportFacadesCache;
Route::get(‘/cache’, function () {
return Cache::get(‘PutkeyNameHere’);
})

What are the major differences between Laravel 4 and Laravel 5.x?

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.

What do you understand by Reverse routing?

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.

What do you understand by Lumen?

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