Laravel Interview Questions and Answers

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 .

* The Laravel version 8, which was released on September 8th, 2020.

* The latest Laravel version is version 9, which was released on February 8, 2022.
The minimum compatible PHP version for Laravel 7 is PHP 7.2.5 and for Laravel 8 is PHP 7.3.0. 
Composer is the package manager for the framework. It helps in adding new packages from the huge community into your laravel application.
 
For example, one of the most used packages for authentication will be Passport, for including that into your project, you can run the below command on your terminal:
composer requires laravel/passport
It generates a file(composer.json) in your project directory to keep track of all your packages. A default composer.json file of your laravel project will look something like below:
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    }
}
The “require” and “require-dev” keys in composer.json specify production and dev packages and their version constraints respectively.
There are several popular features in Laravel. These are enlisted below.
 
* Eloquent ORM
* Query builder
* Reverse routing
* Class auto-loading
* Restful controllers
* Blade template engine
* Lazy collection
* Unit testing
* Database seeding
* Migrations
Laravel 8 released on the 8th of September 2020 with new additional features and some modifications to the existing features.
 
The following list shows the new features of Laravel 8 :
 
* Laravel Jetstream
* Models directory
* Model factory classes
* Migration squashing
* Time testing helpers
* Dynamic blade components
* Rate limiting improvements
Minimum PHP Requirement : First and most importantly, Laravel 9 requires the latest PHP 8 and PHPUnit 8 for testing. That’s because Laravel 9 will be using the newest Symfony v6.0, which also requires PHP 8.
 
Anonymous Stub Migration : Laravel sets to make anonymous stub migration the default behavior when you run the popular migration command:
php artisan make:migration
From Laravel 8.37, the framework now supports anonymous class migration files, and in Laravel 9, it will be the default behavior.
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('people', function (Blueprint $table)
        {
            $table->string('first_name')->nullable();
        });
    }
};

?>
 
New Query Builder Interface : With the new Laravel 9, type hinting is highly reliable for refactoring, static analysis, and code completion in their IDEs. Due to the lack of shared interface or inheritance between Query\Builder, Eloquent\Builder, and Eloquent\Relation. Still, with Laravel 9, developers can now enjoy the new query builder interface for type hinting, refactoring, and static analysis.
<?php

return Model::query()
	->whereNotExists(function($query) {
		// $query is a Query\Builder
	})
	->whereHas('relation', function($query) {
		// $query is an Eloquent\Builder
	})
	->with('relation', function($query) {
		// $query is an Eloquent\Relation
	});
?>
This version added the new Illuminate\Contracts\Database\QueryBuilder interface, as well as the Illuminate\Database\Eloquent\Concerns\DecoratesQueryBuilder trait that will implement the interface in place of the __call magic method.
 
PHP 8 String Functions : Since Laravel 9 targets PHP 8, Laravel merged this PR, suggesting using the newest PHP 8 string functions.
 
These functions include the use of str_contains(), str_starts_with(), and str_ends_with() internally in the \Illuminate\Support\Str class.
 
Laravel 9’s features and improvements listed above are a sneak peek at what is to come. It’ll most definitely bring lots of bug fixes, features, and, of course, many breaking changes.
 
 
 
HTTP middleware is a technique for filtering HTTP requests. Laravel includes a middleware that checks whether application user is authenticated or not.
Aggregates methods of query builder are :

1) max()
2) min()
3) sum()
4) avg()
5) count()
There are many advantages of using the Laravel framework and some of them are listed below:
 
* Laravel is free to use.
* Configuration of application is simple and straightforward.
* The framework supports the Model-View-Controller (MVC) architecture.
* Inbuilt modules and libraries of Laravel help to speed up the development process.
* The performance of Laravel applications is high.
* Routing is easy.
* It has a feature called Eloquent ORM that is used to handle database operations.
* It has a templating engine called Blade.
* Laravel has an inbuilt facility to support unit tests.
* Community support is high.
There are several differences between Laravel and CodeIgniter frameworks, and some main differences are shown in the below table.
 
Laravel Framework CodeIgniter Framework
Relational object-oriented Object-oriented
Supports custom HTTPS routes Does not support HTTPS routes fully
Has authentication class features No built-in authentication features
Has an inbuilt unit testing feature No inbuilt unit testing feature
Use blade templates Does not use blade templates
Not easy to learn for beginners Easy to learn for beginners
Easy to develop REST APIs Not easy to develop REST APIs
Supports ORM Does not support ORM
An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel events provides a simple observer implementation, that allowing you to subscribe and listen for various events/actions that occur in your application.
 
All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.
In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database.
 
Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.

Example :
$validatedData = $request->validate([
            'name' => 'required|max:255',
            'username' => 'required|alpha_num',
            'age' => 'required|numeric',
        ]);
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.
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.
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') }}  
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 following are the pros and cons of the Laravel framework.
 
Pros of Laravel :
* For managing the project dependencies, Laravel uses the Composer allowing developers to mention the package name, version, and the pre-built functionalities that are ready for use in your project, resulting in faster development of the application
* It comes with a blade templating engine that is easy to learn and understand. This is useful while working with the PHP/HTML languages. Web development via Laravel allows the composing of the plain PHP codes in a layout shape, thus helping in improving the execution of complex tasks.
* You can learn Laravel via Laracast that comes with both free and paid videos for easy learning
* Laravel has an object-relational mapper named Eloquent that helps implement the active record pattern and interact with the relational database. It is available as a package for Laravel.
* Laravel has a built-in command-line tool called Artisan support, where users can carry out repetitive tasks quickly and effortlessly
* With the help of the Laravel schema, developers can create database tables and add desired columns via writing a simple migration script
* It comes with a reverse routing feature that makes your application more flexible
 
Cons of Laravel:
* It is challenging to migrate legacy system to Laravel
* It comes with heavy documentation that might be difficult to understand for beginners
* Upgrades aren’t smooth
The composer comes as a dependency manager. If it is not installed on your system, you can install it using this link.
 
After successfully installing the composer on your system, you need to create a project directory for your Laravel project. Later, you need to navigate the path where you have created the Laravel directory and run the following command:
composer create-project laravel/laravel --prefer-dist
This command will help install the Laravel in the current directory. If you want to start Laravel, run the following command.
php artisan serve
Laravel will get started on the development server. Now, run http://localhost:8000/ on your browser. The server requirement is as follows for installing Laravel.
 
* PHP >= PHP version 7.3 or above version
* OpenSSL PHP Extension
* PDO PHP Extension
* Mbstring PHP Extension
* Tokenizer PHP Extension
* XML PHP Extension
* Ctype PHP Extension
* JSON PHP Extension
BCMath PHP Extension
PHP artisan is a command-line tool available in Laravel that comes with a variety of useful commands which help create an application quickly and hassle-free. You will get commands for every important task by default, like database seeding, migration, configuring cache, and many others. 
 
The following are some important PHP artisan commands :
 
php artisan make:controller : Used for creating a Controller file
php artisan make:model : Used for making a Model file
php artisan make:migration : Used for making the Migration file
php artisan make:seeder : Used for making the Seeder file
php artisan make:factory : Used for making the Factory file
php artisan make:policy : Used for making the Policy file
php artisan make:command : Used for making a new artisan command
Middleware provides a mechanism that helps filter the incoming HTTP request to your application. The basic middleware is explained with authentication. If the user is not authenticated, they will be redirected to the login page, and if the user is authenticated, they will be allowed for further processing. All this is possible with the help of the middleware.
 
Laravel has a php artisan make:middleware <middleware_name> command, helping define the new middleware within your application. By default, the middleware will get stored in the app/Http/Middleware directory. 
 
If you want to run middleware for every HTTP request, list the middleware class within the $middleware property of the app/Http/Kernel.php class. If you want to assign middleware specifically, assign it in the key-value pair at the app/Http/Kernel.php class $routeMiddleware property.
Laravel uses Blade templating engine. Blade is a powerful but simple templating engine of Laravel. Blade allows you to use plain php code into view and it compiles and cached view until it’s modified. Blade view files are stored in resources/views directory with extension .blade.php.
 
An example of blade file is :
<!-- /resources/views/alert.blade.php -->
<div class="alert alert-danger">
   {{ $slot }}
</div>
 
In the variable $slot we can assign any value which we want to inject to component. Component looks like :
@component('alert')
   <strong>Whoops!</strong> Something went wrong!
@endcomponent
@component is the blade directive here.
First let's understand CSRF - It's cross-site request forgery attack. Cross-site forgeries are a type of malicious exploit where unauthorized commands can be executed on behalf of the authenticated user. Laravel generates a CSRF "token" automatically for each active user session. This token is used to verify that the authenticated user is the one actually making the requests to the application.
<form method="POST" action="/profile">
   @csrf
   ...
</form>
If you're defining an HTML form in your application you should include a hidden CSRF token field in the form so that middleware (CSRF Protection middleware) can validate the request. VerifyCsrfToken middleware is included in web middleware group. @csrf blade directive can be used to generate the token field.
 
If using JS driven application then you can attach your js HTTP library automatically attach the CSRF token with every HTTP request. resources/js/bootstrap.js is the default file which registers value of csrf-token meta tag with HTTP library.
 
To remove URIs from CSRF in verifyCsrfToken we can use $except property where can provide URLs which we want to exclude.
Migrations are like version control for the database. With migration team can easily modify the database schema, migrations are paired with Laravel’s schema builder to easily build application’s db schema. With Laravel Schema facade creating and manipulating tables across the application is very easy. Artisan command to create migration schema is php artisan make:migration create_employeess_table. New migrations will be stored in database/migrations directory. Each migration will along with migration name contains the timestamp of the creation of file which helps Laravel to order migrations.
 
The --table and --create options may be used to indicate the name of the table and whether the migration will be creating a new table. These options pre-fill the generated migration stub file with the specified table:
 
* php artisan make:migration create_employees_table --create=employees

* php artisan make:migration add_departments_to_employee_table --table=employees
Following are some official packages provided by Laravel:
 
Authentication :
Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box.
//Make authorization views and scaffolding
php artisan make:auth
Passport :
* In Short, Laravel provides Passport for API Authentication.
* Laravel Passport is an OAuth2 server and API authentication package that is simple to use

Cashier :
* Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services
 
Scout :
* Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models.
* Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records
* Currently, Scout ships with an Algolia driver; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations.

Socialite :
* Laravel's Socialite package makes it simple to authenticate your users to social login
* Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket.
Disable CSRF protection for all routes In Laravel:
Remove or comment out this line in app\Http\Kernel.php

\App\Http\Middleware\VerifyCsrfToken::class,
 
To turn off or disable CRSF protection for some specific routes in Laravel :
open "app/Http/Middleware/VerifyCsrfToken.php" file and add your routes in $except array.
namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
		'stripe/*',
		'payment/verify/{id}/*',
		'some/route/path',
    ];
MVC architecture is a design pattern that is used to develop web applications. It consists of three components named Model, View and Controller. MVC design pattern also helps to speed up the development of the web application.
 
Model : In MVC architecture, the letter M stands for Models. Model is the central component of the MVC design pattern. It manages the data in the application.

View : In MVC architecture, the letter V stands for Views. A view displays data to the user.

Controller : In MVC architecture, the letter C stands for Controllers. A controller is used to handle user requests.
The below diagram shows the interactions within the MVC design pattern.

MVC architecture in Laravel
The following list shows the available router methods in Laravel:
 
* Route::get($uri, $callback);
* Route::post($uri, $callback);
* Route::put($uri, $callback);
* Route::patch($uri, $callback);
* Route::delete($uri, $callback);
* Route::options($uri, $callback);
Maintenance mode is used to put a maintenance page to customers and under the hood, we can do software updates, bug fixes, etc. Laravel applications can be put into maintenance mode using the below command:
php artisan down
And can put the application again on live using the below command:
php artisan up
Also, it is possible to access the website in maintenance mode by whitelisting particular IPs.
Seeders in Laravel are used to put data in the database tables automatically. After running migrations to create the tables, we can run `php artisan db:seed` to run the seeder to populate the database tables.
 
We can create a new Seeder using the below artisan command:
php artisan make:seeder [className]
It will create a new Seeder like below:
<?php

use App\Models\Auth\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        factory(User::class, 10)->create();
    }
}
The run() method in the above code snippet will create 10 new users using the User factory.
Soft Delete means when any data row is deleted by any means in the database, we are not deleting the data but adding a timestamp of deletion.
 
We can add soft delete features by adding a trait in the model file like below.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {

    use SoftDeletes;

    protected $table = 'posts';

    // ...
}
With Laravel, each database table can have a model representation using a model file which can be used to interact with that table using Laravel Eloquent ORM.
 
We can create a model using this artisan command:
php artisan make:model Post
This will create a file in the models’ directory and will look like below :
 
class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [];
}
Relationships in Laravel are a way to define relations between different models in the applications. It is the same as relations in relational databases.
 
Different relationships available in Laravel are:
 
* One to One
* One to Many
* Many to Many
* Has One Through
* Has Many Through
* One to One (Polymorphic)
* One to Many (Polymorphic)
* Many to Many (Polymorphic)

Relationships are defined as a method on the model class. An example of One to One relation is shown below.

We can also define One to Many relationships like below :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * Get the addresses for the User.
     */
    public function addresses()
    {
        return $this->hasMany(Address::class);
    }
}
?>

The above method phone on the User model can be called like : `$user->phone` or `$user->phone()->where(...)->get()`.

We can also define One to Many relationships like below :

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * Get the addresses for the User.
     */
    public function addresses()
    {
        return $this->hasMany(Address::class);
    }
}
?>


Since a user can have multiple addresses, we can define a One to Many relations between the User and Address model. Now if we call `$user->addresses`, eloquent will make the join between tables and it will return the result.

Throttling is a process to rate-limit requests from a particular IP. This can be used to prevent DDOS attacks as well. For throttling, Laravel provides a middleware that can be applied to routes and it can be added to the global middlewares list as well to execute that middleware for each request.
 
Here’s how you can add it to a particular route :
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});
This will enable the /user route to be accessed by a particular user from a particular IP only 60 times in a minute.
You can register service providers in the config/app.php configuration file that contains an array where you can mention the service provider class name.
It is a technique in which one object is dependent on another object.

There are three types of dependency injection :

* Constructor injection
* setter injection
* interface injection.
It is a database query builder that provides convenient, faster interface to create and run database queries.
This function is used to dump contents of a variable to the browser. The full form of dd is Dump and Die.
delete() : remove all record from the database table.

softDeletes() :
It does not remove the data from the table. It is used to flag any record as deleted.
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 :
* Numbers
* Addresses
* DateTime
* Payments
* Lorem text
Insert() : This function is simply used to insert a record into the database. It not necessary that ID should be autoincremented.

InsertGetId() : This function also inserts a record into the table, but it is used when the ID field is auto-increment.
There are seven restful resource controllers in Laravel.
 
The following table shows the actions handled by the restful resource controllers in a Laravel application.
 
Verb Path Action Route Name Use
GET /users index users.index get all users
GET /users/create create users.create create a new user
POST /users store users.store store user details
GET /users/{user} show users.show get user details
GET /users/{user}/edit edit users.edit edit user
PUT/PATCH /users/{user} update users.update update user
DELETE /users/{user} destroy users.destroy delete user
Laravel authentication is the process of verifying application users. It can be achieved by identifying the user’s username and password. Some other parameters may also use for authentication. If user credentials are valid, then the user is authenticated.
 
Laravel uses guards and providers for the authentication process. Guards define how users are authenticated for each request while providers define how users are retrieved from your persistent storage.
There are several differences between GET and POST methods, and some of the important differences are listed in the below table.
GET Method POST Method
Request data from a specific resource Send data to a server
Parameters are included in the URL Parameters are included in the body
Data is visible in the URL Data is not visible in the URL
Only allowed characters are ASCII characters Both ASCII characters and binary data are allowed
There is a limitation on data length No limitation on data length
The request remains in the browser history The request does not remain in the browser history
The request is possible to bookmark The request is not possible to bookmark
Can be cached Cannot be cached
Security is less compared to the POST method Security is high compared to the GET method
Cannot be used to send sensitive data such as passwords Can be used to send sensitive data such as passwords
It is a server management tool for PHP applications. It is a great alternative if you are not planning to manage your own servers.
 
Note : Click here (the official page of Laravel Forge) to learn more about Laravel Forge.
Use the enableQueryLog method to enable query log in Laravel
DB::connection()->enableQueryLog(); 
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();
The syntax to clear cache in Laravel is given below :
 
* php artisan cache: clear
* php artisan config: clear
* php artisan cache: clear
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.
We can use whereBetween() method to retrieve the data between two dates with Query.
 
Syntax :
Blog::whereBetween('created_at', [$date1, $date2])->get();
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.
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');  
})

Facades in Laravel

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.
Laravel's Contracts are the set of interfaces which are responsible for defining the core functionality of services provided by the Laravel framework.
Laravel-Contracts
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.
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();  
Laravel provides @yield for defining a section in a layout, getting the content from the child page, and submitting it to a master page. So whenever you use Laravel to execute the blade file, it first checks whether you have extended the master layout or not. If so, it moves to the master layout and commences getting the @sections.
In Laravel, the with() function is used to eager load. Rather than using two or more separate queries for fetching the data from a database, you can use the with() method after the first command. You will get a better user experience as you do not have to wait longer to fetch the data from the database.
In Laravel, tinker is a powerful REPL tool used to interact with the Laravel application using the command line in an interactive shell. It comes with the release version of 5.4, extracted in a separate package.
 
For installing Tinker, run the following command :
composer require laravel/tinker
For executing Tinker, execute the following command :
php artisan tinker
This method is used to update an existing record in a database if the condition is matched or created if there is no matching record. It will return the boolean value. 
 
You can use the following syntax :
DB::table('blogs')->updateOrInsert([Conditions],[fields with value]);
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.
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  
}