Types of relationship in Laravel Eloquent are: 1) One To One 2) One To Many 3) Many To Many 4) Has Many Through, and 5) Polymorphic Relations.
Author: saqibkhan
-
Authentication
Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated.
Command
Laravel uses the following command to create forms and the associated controllers to perform authentication −
php artisan make:authThis command helps in creating authentication scaffolding successfully, as shown in the following screenshot −

Controller
The controller which is used for the authentication process is HomeController.
<?php namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; class HomeController extends Controller{ /**
*/ public function __construct() {* Create a new controller instance. * * @return void
} /**$this->middleware('auth');
*/ public function index() {* Show the application dashboard. * * @return \Illuminate\Http\Response
} }return view('home');As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below −
Login

Registration

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
Manually Authenticating Users
Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password.
Consider the following lines of code for LoginController which includes all the functions for authentication −
<?php // Authentication mechanism namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class LoginController extends Controller{ /**
*/ public function authenticate() {* Handling authentication request * * @return Response
} }if (Auth::attempt(['email' => $email, 'password' => $password])) { // Authentication passed... return redirect()->intended('dashboard'); } -
CSRF Protection
CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks.
Laravel offers CSRF protection in the following way −
Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user.
Implementation
The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection −
- CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −
<form method = "POST" action="/profile"> {{ csrf_field() }} ... </form>- You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request.
- The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library.
Form without CSRF token
Consider the following lines of code. They show a form which takes two parameters as input: email and message.
<form> <label> Email </label>
<label> Message </label> <input type="text" name = "message"/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form><input type = "text" name = "email"/> <br/>The result of the above code is the form shown below which the end user can view −

The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks.
Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below −
public function postContact(Request $request) { return $request-> all(); }Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks.
Form with CSRF token
The following lines of code shows you the form re-designed using CSRF tokens −
<form method = ”post” > {{ csrf_field() }} <label> Email </label> <input type = "text" name = "email"/> <br/> <label> Message </label> <input type = "text" name = "message"/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form>The output achieved will return JSON with a token as given below −
{ "token": "ghfleifxDSUYEW9WE67877CXNVFJKL", "name": "TutorialsPoint", "email": "[email protected]" }This is the CSRF token created on clicking the submit button.
-
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.
-
What does ORM stand for?
ORM stands for Object Relational Mapping
-
Explain validation concept in Laravel.
Validations are an important concept while designing any Laravel application. It ensures that the data is always in an expected format before it stores into the database. Laravel provides many ways to validate your data.
Base controller trait uses a ValidatesRequests class which provides a useful method to validate requests coming from the client machine.
-
Contracts
Laravel contracts are a set of interfaces with various functionalities and core services provided by the framework.
For example, Illuminate\Contracts\Queue\Queue contract uses a method which is needed for queuing jobs and Illuminate\Contracts\Mail\Mailer uses the method for sending emails.
Every contract defined includes corresponding implementation of the framework. All the Laravel contracts are available in the GitHub repository as mentioned below −
This repository provides a variety of contracts available in the Laravel framework which can be downloaded and used accordingly.
Important Points
While working with Laravel contracts, please note the following important points −
- It is mandatory to define facades in the constructor of a class.
- Contracts are explicitly defined in the classes and you need not define the contracts in constructors.
Example
Consider the contract used for Authorization in Laravel which is mentioned below −
<?php namespace Illuminate\Contracts\Auth\Access; interface Authorizable{ /**
*/ public function can($ability, $arguments = []); }* Determine if the entity has a given ability. * * @param string $ability * @param array|mixed $arguments * @return boolThe contract uses a function can which includes a parameter named ability and arguments which uses the user identification in the form of an array.
You will have to define a contract as shown in the syntax below −
interface <contract-name>Contracts are used like facades for creating robust, well-tested Laravel applications. There are various practical differences with usage of contracts and facades.
The following code shows using a contract for caching a repository −
<?php namespace App\Orders; use Illuminate\Contracts\Cache\Repository as Cache; class Repository{ /**
*/ protected $cache; /*** The cache instance.
*/ public function __construct(Cache $cache) {* Create a new repository instance. * * @param Cache $cache * @return void
} }$this->cache = $cache;Contract contains no implementation and new dependencies; it is easy to write an alternative implementation of a specified contract, thus a user can replace cache implementation without modifying any code base.
-
What are the advantages of using Laravel?
Here are important benefits of Laravel:
- Laravel has blade template engine to create dynamic layouts and increase compiling tasks.
- Reuse code without any hassle.
- Laravel provides you to enforce constraints between multiple DBM objects by using an advanced query builder mechanism.
- The framework has an auto-loading feature, so you don’t do manual maintenance and inclusion paths
- The framework helps you to make new tools by using LOC container.
- Laravel offers a version control system that helps with simplified management of migrations.
-
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.
-
Explain the concept of events in Laravel.
An event is an occurrence or action that help you to subscribe and listen for events that occur in Laravel application. Some of the events are fired automatically by Laravel when any activity occurs.