Wednesday, 11 December 2019

Laravel Questions and Answers






1. Define composer.
ANS:  It is an application-level package manager for PHP. It provides a standard format for managing PHP software dependencies and libraries. we can download the packages by using composer

2.What is HTTP middleware?
ANS: HTTP middleware is a technique for filtering HTTP requests. 

In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. Middle wares are 3types. They are
 i). Global Middleware:  if you want a middleware to run during every HTTP request to your application then list the middleware class in the $middleware property of your app/Http/Kernel.php class.
    Kernel.php : heare webguard is a middle ware file. which is located at app/http/middleware 



ii). Route Middleware:  if you would like to assign middleware to specific routes then add your middleware class in $routeMiddleware array of app/Http/Kernel.php file and add middleware to routes/web.php file
Ex:
 web.php file:
  Route::get("/data",[IndexController::class, 'index'])->middleware('guard');
 
 Kernal.php 



iii). Middleware Groups: Some times you may want to group several middlewares under a single key to make them easier to assign to routes. You may complish this using the $middlewareGroups property of your HTTP kernel file.
  Ex: 
   


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.
ex : 
php artisan make:middleware <MiddelwareName>
// Example php artisan make:middleware UserMiddelware

Now UserMiddelware.php file will create in app/Http/Middleware and update app/http/Kernel.php file with middleware code.

3. Explain Events & Listners in Laravel ?
  
An event is an action or occurrence recognized by a program that may be handled by the program or code. 
All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.

  
Events:
  • ->Events represent something that has happened in your application, such as a user registering, a new post being created, or a payment being made.
  • ->Laravel's event system provides a way to notify other parts of your application that an event has occurred.
  • ->Events are usually represented as simple PHP classes that contain data related to the event.
  • ->You can create custom events by extending Laravel's base Event class or by generating them using the php artisan make:event command.

Listeners:

  • ->Listeners are responsible for responding to events. They contain the logic that should be executed when a specific event occurs.
  • ->Listeners are also represented as PHP classes and should implement the Illuminate\Contracts\Queue\ShouldQueue interface if you want them to be queued for asynchronous execution.
  • ->You can create custom listeners by generating them using the php artisan make:listener command.
This will generate an "UserRegistered" event class in the 'app/Events' directory.










4. How to install laravel using composer ?
ANS : You can install Laravel via composer by running below command.
composer create-project laravel/laravel <your-project-name> <version>
   Features of Laravel

                      Eloquent ORM
§  Query builder available
§  Reverse routing
§  Restful controllers
§  Migrations
§  Database Seeding
§  Automatic pagination
§  Unit testing
§  Homestead

5.What do you mean by bundles?
In Laravel, bundles are referred to as packages. These packages are used to increase the functionality of Laravel. A package can have views, configuration, migrations, routes, and tasks 
 Ex: 1.Breeze (
login, registration, password reset, email verification, and password confirmation)
2. 
Cashier (it handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs).
3. 
Laravel Passport (it provides a full OAuth2 server implementation)
4.
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs.

6.Explain reverse routing in Laravel.
   Reverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible. In traditional routing, you define routes that map specific URLs to controller actions. Reverse routing takes this a step further by allowing you to generate URLs dynamically based on the names you've assigned to your routes. This can be incredibly useful, especially when building links in your views or generating URLs in your application.

Web.php file

View page

 


 7. Explain traits in Laravel.

Ans : Laravel traits are a group of functions that you include within another class. A trait is like an abstract class. You cannot instantiate directly, but its methods can be used in concreate class.
if you wan to create custom traits then create it in app/traits folder.

What  PSR (PHP standard Recomandations) are following in Laravel ?
      PSR-2 and PSR-4 following in laravel (Latest PSR is 20)

8.Where will you define Laravel's Facades?
Facades provide a static interface to classes available in the Laravel service container, allowing you to interact with these classes in a clean and concise manner. Facades provide a "static" interface to classes that are available in the application's service container.All facades of Laravel have defined in vendor\laravel\framework\src\Illuminate\Support\Facades namespace.

9. What is $fillable and $guarded in Laravel model?
Ans:  
In Laravel, both $fillable and $guarded are used for controlling mass assignment, $fillable need to assign in models. We can only access the $fillable array values only. Attributes not listed in the $fillable array will be guarded against mass assignment, meaning they cannot be assigned in this way.

protected $fillable = ['name', 'email', 'password'];


 $guarded  is opposite to $fillable. The $guarded property is also an array, but it specifies which attributes should be guarded against mass assignment. In other words, attributes listed in $guarded will not be mass-assigned using methods like create or update.

protected $guarded = ['admin']; // 'admin' attribute is guarded

   
10.What is service containers and service providers in Laravel?

Service container is a tool used for performing dependency injection in Laravel.

Dependency Injection means that class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods. Mostly constructor is used for injecting the dependency.

Uses of service containers:

 Binding Services: The service container allows you to bind classes or values into it. This means you can tell the container how to create instances of a particular class or provide a specific value when requested. Resolution: When you need an instance of a class or a value, you can ask the service container to resolve it for you. The container will take care of instantiating the class and resolving its dependencies, ensuring that you get a fully configured object. Lazy Loading: The service container can defer the creation of objects until they are actually needed. This helps improve performance by only creating objects when necessary.

Dependency Injection: Laravel's service container plays a crucial role in enabling dependency injection. When you type-hint a class or interface in a method or constructor, Laravel will automatically inject the appropriate dependencies for you, thanks to the service container.

Singletons: You can bind a class or value as a singleton in the service container. This means that only one instance of the object will be created and reused whenever it is requested.

service providers are responsible for registering and configuring services within the service container. create a new service provider using the artisan command: php artisan make:provider LoggerServiceProvider

This command will generate a new service provider file in the app/Providers directory, named LoggerServiceProvider.php. Open the LoggerServiceProvider.php file and locate the register method. This method is where you can register your service into the container. Bind the Logger class to the container like this:


use Illuminate\Support\ServiceProvider;
use App\Services\Logger; // Replace with the actual namespace of your Logger class

class LoggerServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('logger', function ($app) {
            return new Logger();
        });
    }
}


In this example, we've bound a class named "logger" to the container. When you resolve "logger" from the container, it will create a new instance of the Logger class.

  1. Next, you need to add your service provider to the config/app.php file in the providers array:
  2. 'providers' => [
        // ...
        App\Providers\LoggerServiceProvider::class,
        // ...
    ],
After adding the service provider, you can use the "logger" service throughout your Laravel application:

$logger = app('logger'); // Resolve the Logger instance from the container
$logger->log('This is a log message');



11.Explain dependency injection and their types.
It is a technique in which one object is dependent on another object. There are three types of dependency injection: 1) Constructor injection, 2) setter injection, and 3) interface injection.

12.How can you reduce memory usage in Laravel?
While processing a large amount of data, you can use the cursor method in order to reduce memory usage.

13.List available types of relationships in Laravel Eloquent.
Types of relationship in Laravel Eloquent are:
1) One To One 
     class User extends Model
{
/**
* Get the phone associated with the user.
*/
public function phone()
{
return $this->hasOne(Phone::class);
}
}

     
Belongs to Relationship:
 
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}

2) One To Many
    class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}


// Inverse or belongs to
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}

3) Many To Many
     class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany(Role::class);
}
}

Inverse / belognsto

class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}

4) Has Many Through, and

    class Project extends Model
{
/**
* Get all of the deployments for the project.
*/
public function deployments()
{
return $this->hasManyThrough(Deployment::class, Environment::class);
}
}

5) Polymorphic Relations.



14.Why are migrations important?
Migrations are important because it allows you to share application by maintaining database consistency. Without migration, it is difficult to share any Laravel application. It also allows you to sync database.

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.

15.Define Lumen
Lumen is a micro-framework. It is a smaller, and faster, version of a building Laravel based services, and REST API's.

16.Explain PHP artisan
An artisan is a command-line tool of Laravel. It provides commands that help you to build Laravel application without any hassle.

17.Which class is used to handle exceptions?
     Laravel exceptions are handled by App\Exceptions\Handler class.

18.What is dd()  & closure function?
This function is used to dump contents of a variable to the browser. The full form of dd is Dump and Die. 
Closure is an anonymous function. Closures are also commonly referred to as anonymous functions or lambda functions.

 

19. List out common artisan commands used in Laravel.
Laravel supports following artisan commands:
  • PHP artisan down;
  • PHP artisan up;
  • PHP artisan make:controller;
  • PHP artisan make:model;
  • PHP artisan make:migration;
  • PHP artisan make:middleware;
20.Explain faker in Laravel.
It is a type of module or packages which are used to create fake data. This data can be used for testing purpose.
It is can also be used to generate: 1) Numbers, 2) Addresses, 3) DateTime, 4) Payments, and 5) Lorem text.

21.List basic concepts in Laravel?
Following are basic concepts used in Laravel:
  • Routing
  • Eloquent ORM
  • Middleware
  • Security
  • Caching
  • Blade Templating
22.Define Implicit Controller.
Implicit Controllers help you to define a proper route to handle controller action. You can define them in route.php file with Route:: controller() method.

23.Which file is used to create a connection with the database?
To create a connection with the database, you can use .env file.

24.Name some Inbuilt Authentication Controllers of Laravel.
Laravel installation has an inbuilt set of common authentication controllers. These controllers are:
  • RegisterController
  • LoginController
  • ResetPasswordController
  • ForgetPasswordController
25.Define Laravel guard.
Laravel guard is a special component that is used to find authenticated users. The incoming requested is initially routed through this guard to validate credentials entered by users. Guards are defined in ../config/auth.php file.

26.What is Laravel API rate limit?
It is a feature of Laravel. It provides handle throttling. Rate limiting helps Laravel developers to develop a secure application and prevent DOS attacks.

27.Explain collections in Laravel.
Collections is a wrapper class to work with arrays. Laravel Eloquent queries use a set of the most common functions to return database result.

28.What is the use of DB facade?
DB facade is used to run SQL queries like create, select, update, insert, and delete.

29.State the difference between authentication and authorization.
Authentication means confirming user identities through credentials, while authorization refers to gathering access to the system.

30.Explain to listeners.
Listeners are used to handling events and exceptions. The most common listener in Laravel for login event is LoginListener.

31.What are policies classes?
Policies classes include authorization logic of Laravel application. These classes are used for a particular model or resource.

32.How to rollback last migration?
Use need to use artisan command to rollback the last migration.

33.State the difference between CodeIgniter and Laravel.
Parameter
CodeIgniter
Laravel
Support of ORM
CodeIgniter does not support Object-relational mapping.
Laravel supports ORM.
Provide Authentication
It does provide user authentication.
It has inbuilt user authentication.
Programming Paradigm
It is component-oriented.
It is object-oriented.
Support of other Database Management System
It supports Microsoft SQL Server, ORACLE, MYSQL, IBM DB2, PostgreSQL, JDBC, and orientDB compatible.
It supports PostgreSQL, MySQL, MongoDB, and Microsoft BI, but CodeIgniter additionally supports other databases like Microsoft SQL Server, DB2, Oracle, etc.
HTTPS Support
Laravel supports custom HTTPS routes. The programmers can create a specific URL for HTTPS route they have defined.
CodeIgniter partially support HTTPS. Therefore, programmers can use the URL to secure the data transmission process by creating PATS.

34.What is an Observer?
Model Observers is a feature of Laravel. It is used to make clusters of event listeners for a model. Method names of these classes depict the Eloquent event. Observers classes methods receive the model as an argument.

35.What is carbon in laravel?
  Carbon is PHP Library working with dates and time.
 
use Carbon\Carbon;
$current = Carbon::now();

36.What is Localization?
It is a feature of Laravel that supports various language to be used in the application. A developer can store strings of different languages in a file, and these files are stored at resources/views folder. Developers should create a separate folder for each supported language.

37.Define hashing in Laravel.
It is the method of converting text into a key that shows the original text. Laravel uses the Hash facade to store the password securely in a hashed manner.

38.How to share data with views?
To pass data to all views in Laravel use method called share(). This method takes two arguments, key, and value.
Generally, share() method are called from boot method of Laravel application service provider. A developer can use any service provider, AppServiceProvider, or our own service provider.

39.Explain web.php route.
Web.php is the public-facing "browser" based route. This route is the most common and is what gets hit by the web browser. They run through the web middleware group and also contain facilities for CSRF protection (which helps defend against form-based malicious attacks and hacks) and generally contain a degree of "state" (by this I mean they utilize sessions).

40. what are default route files in the routes folder in Laravel?

Below are the four default route files in the routes folder in Laravel:
web.php - For registering web routes.
api.php - For registering API routes.
console.php - For registering closure based console commands.
channel.php - For registering all your event broadcasting channels that your application support.

41. How will you register service providers ?
 Ans.
You can register service providers in the config/app.php configuration file that contains an array where you can mention the service providers class name.

Service providers are used for a variety of purposes, such as:

  • Binding interfaces to their implementations in the service container.
  • Registering singletons (instances that are shared across the application).
  • Defining aliases for classes (shorter names for classes in the container).
  • Registering custom Blade directives.
  • Bootstrapping packages or third-party components.

No comments:

Post a Comment