Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Saturday, February 20, 2021

Some Rare Questions Asked about Laravel

  Here we would love to share with you frequently asked Laravel Interview Questions and answers. Laravel 6 and 7 has been added great new features and improvements. So here, you can get and learn laravel questions and answers.

Laravel is a free and open-source PHP framework that follows the model–view–controller design (MVC) pattern.

1) 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 2015, Laravel was voted as one of the most popular PHP frameworks along with Symfony, Nette, CodeIgniter, and Yii2 .

2) What are the main features of Laravel?

Some of the main features of Laravel are:

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

3) What do you understand by Eloquent ORM?

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.


4) What is Query Builder in Laravel?

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.


5) Write down the name of some aggregates methods provided by the Laravel’s query builder.

Some of the methods that Query Builder provides are:

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

6) What is routing?

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.


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

  1. {{ HTML::link_to_action(‘users@login’) }}  

8) How will you describe Bundles in Laravel?

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.


9) What is a composer, and how can we install Laravel by the composer?

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>

10) Does Laravel support caching?

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.


11) How to clear cache in Laravel?

The syntax to clear cache in Laravel is given below:

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

12) 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  

Now, UserMiddleware.php file will be created in app/Http/Middleware.

13) What do you understand by database migrations in Laravel? How can we use it?

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.


14) What do you know about Service providers in Laravel?

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.


15) How can we get data between two dates using Query in Laravel?

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

Example

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


16) What do you know about CSRF token in Laravel? How can someone turn off CSRF protection for a specific route?

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

1
2
3
4
5
6
classVerifyCsrfToken extends BaseVerifier 
protected $except = [ 
          'Pass here your URL'
      ]; 

17) List some official packages provided by Laravel?

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.


18) What do you understand by Unit testing?

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.


19) 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 Illuminate\Support\Facades namespace. Hence, it is easy to use.

Example

 

 

1
2
3
4
use Illuminate\Support\Facades\Cache; 
     Route::get('/cache', function () { 
return Cache::get('PutkeyNameHere'); 
}) 

 

 

20) How can we check the Laravel current version?

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

Php artisan -version  

21) How will you explain dd() function in Laravel?

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

22) What do you know about PHP artisan? Mention some artisan command.

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.


23) How will you explain Events in Laravel?

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.

24) What are the validations in Laravel?

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.


25) 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:

  1. composer create-project –prefer-distlaravel/lumen blog  

26) Which template engine is used by Laravel?

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.


27) Explain the Service container and its advantages.

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

28) What do you know about Laravel Contracts?

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

29) How will you explain homestead in Laravel?

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.


30) What are the differences between Laravel and Codeigniter?

LaravelCodeigniter
Laravel is a framework with an expressive, elegant syntax.Codeigniter is a powerful framework based on PHP.
Laravel is built for the latest version of PHP.Codeigniter is an older, more mature framework.
Laravel is more object-oriented as compared to Codeigniter.Codeigniter is less object-oriented as compared to Laravel.
Laravel can produce model-view-controller, active-record, observer, dependency injection, singleton, restful, façade, event-driven, MTV, and HMVC design patterns.Codeigniter can produce active-record, model-view-controller, and HMVC design patterns.
Laravel supports ORM.Codeigniter does not support ORM
Laravel needs 1 GB memory.Codeigniter needs 256 GB memory.
Laravel has built-in user authentication support.Codeigniter does not have in-built user authentication support.

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

We can get the user’s IP address using:


32) How can we use the custom table in Laravel?

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

1
2
3
class User extends Eloquent{ 
protected $table="my_user_table"

33) What is the use of the Eloquent cursor() method in Laravel?

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

1
2
3
foreach (Product::where('name', 'bar')->cursor() as $flight) { 
//make some stuff 

34) How will you create a helper file in Laravel?

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

1
2
3
"files": [ 
"app/helpers.php" 

in the “autoload” variable.

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


35) What are the requirements for Laravel 6?

  • PHP version >= 7.2.0
  • JSON PHP Extension
  • BCMath PHP Extension
  • Ctype PHP Extension
  • Mbstring PHP Extension
  • XML PHP Extension.
  • Tokenizer PHP Extension
  • OpenSSL PHP Extension
  • PDO PHP Extension

36) In which directory controllers are kept in Laravel?

Controllers are kept in app/http/Controllers directory.


37) What is the use of PHP compact function?

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.


38) 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.

39) Explain some benefits of Laravel over other PHP frameworks.

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.

40) Which types of relationships are available in Laravel Eloquent?

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

41) What do you understand by ORM?

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.


42) How can we implement a package in Laravel?

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.

43) 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

1
2
3
4
5
6
trait Sharable { 
public function share($item) 
  
return 'share this item'; 
  
}

We can then include this Trait within other classes like:

1
2
3
4
5
6
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:

1
2
3
4
$post = new Post; 
echo $post->share(''); // 'share this item'  
$comment = new Comment; 
echo $comment->share(''); // 'share this item' 

44) How can someone change the default database type in Laravel?

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.


45) How can we use maintenance mode in Laravel 6?

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 6, simply by executing the below command:

1
2
3
4
5
// Enable maintenance mode 
php artisan down 
   
// Disable maintenance mode 
php artisan up 

46) How can we create a record in Laravel using eloquent?

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

1
2
3
4
5
6
public functionsaveProduct(Request $request )  {
 $product = new product; 
 $product->name = $request->name; 
 $product->description = $request->name; 
 $product->save(); 
}

47) How can we check the logged-in user info in Laravel?

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

Example

1
2
3
if(Auth::check()){ 
 dd(Auth::User()); 

48) How will you describe Fillable Attribute in a Laravel model?

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 the Database.

Code Source

1
2
3
4
class User extends Model { 
protected $fillable = ['name', 'email', 'mobile'];  
// All fields inside $fillable array can be mass-assigned 

49) 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

1
2
3
4
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.


50) 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

1
2
3
4
5
6
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.’

51) What are common HTTP error codes?

The most common HTTP error codes are:

  • Error 404 – Displays when Page is not found.
  • Error- 401 – Displays when an error is not authorized

52) 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;

53) Differentiate between delete() and softDeletes().

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

54) How can you make real-time sitemap.xml file in Laravel?

You can create all web pages of a website to tell the search engine about the organizing site content. The crawlers of the search engine read this file intelligently to crawl a website.

55) How will you check table is exists or in the database?

Use hasTable() Laravel function to check the desired table is exists in the database or not.

55) What is the significant difference between insert() and insertGetId() function in Laravel?

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

56) Explain active record concept in Laravel.

In active record, class map to your database table. It helps you to deal with CRUD operation.

57) List basic concepts in Laravel?

Following are basic concepts used in Laravel:

  • Routing
  • Eloquent ORM
  • Middleware
  • Security
  • Caching
  • Blade Templating

58) What is the use of DB facade?

DB facade is used to run SQL queries like create, select, update, insert, and delete.

59) What is Ajax in Laravel?

Ajax stands for Asynchronous JavaScript and XML is a web development technique that is used to create asynchronous Web applications. In Laravel, response() and json() functions are used to create asynchronous web applications.

60) What is a session in Laravel?

Session is used to pass user information from one web page to another. Laravel provides various drivers like a cookie, array, file, Memcached, and Redis to handle session data.

61) How to access session data?

Session data be access by creating an instance of the session in HTTP request. Once you get the instance, use get() method with a “Key” as a parameter to get the session details.

62) State the difference between authentication and authorization.

Authentication means confirming user identities through credentials, while authorization refers to gathering access to the system.

63) Explain Response in Laravel.

All controllers and routes should return a response to be sent back to the web browser. Laravel provides various ways to return this response. The most basic response is returning a string from controller or route.

64) What is query scope?

It is a feature of Laravel where we can reuse similar queries. We do not require to write the same types of queries again in the Laravel project. Once the scope is defined, just call the scope method when querying the model.

65) What is namespace in Laravel?

A namespace allows a user to group the functions, classes, and constants under a specific name.

66) What is the use of the bootstrap directory?

It is used to initialize a Laravel project. This bootstrap directory contains app.php file that is responsible for bootstrapping the framework.

67) What is the default session timeout duration?

The default Laravel session timeout duration is 2 hours.

68) In which folder robot.txt is placed?

Robot.txt file is placed in Public directory.

69) Explain API.PHP route.

Its routes correspond to an API cluster. It has API middleware which is enabled by default in Laravel. These routes do not have any state and cross-request memory or have no sessions.

70) How to generate a request in Laravel?

Use the following artisan command in Laravel to generate request:

php artisan make:request UploadFileRequest

71) What are the advanced features of Laravel 6.0?

The latest version 6.0 is incorporated with a number of latest features such as Laravel vapor compatibility, semantic visioning, job middleware, lazy collections, eloquent sub-query enhancements, Laravel users interface, etc. The Laravel 6.0 released on 3rd September 2019 with latest and unique features.

Advanced Features of Laravel 6.0
  • Laravel Vapor Compatibility
  • Semantic Versioning
  • Job Middleware
  • Laravel User Interface (UI)
  • Eloquent Subquery Enhancements
  • Improved Authorization Responses
  • Lazy Collections

72) How to pass CSRF token with ajax request?

In between head tag put the below line of code:-

1
<meta name="csrf-token" content="{{ csrf_token() }}">

In ajax, add the below line of code:-

1
2
3
4
5
$.ajaxSetup({
   headers: {
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

73) What is the latest version of laravel?

The latest version of Laravel is 6.0. It released on 3rd September 2019.

74) How to use skip() and take() in Laravel Query?

We can use skip() and take() both methods to limit the number of results in the query. skip() is used to skip the number of results and take() is used to get the number of result from the query.

Example

1
2
3
4
5
$posts = DB::table('blog')->skip(5)->take(10)->get();
 
// skip first 5 records
 
// get 10 records after 5

75) How to extend login expire time in Auth?

You can extend the login expire time with config\session.php this file location. Just update lifetime the variables value. By default it is ‘lifetime’ => 120. According to your requirement update this variable.

76) How to redirect form controller to view file in laravel?

We can use :-

1
2
3
4
return redirect('/')->withSuccess('You can type your message here');
return redirect('/')->withErrors('You can type your message here');
return redirect('/')->with('variableName', 'You can type your message here');
return redirect('/')->route('PutRouteNameHere');

77) How to get current route name?

request()->route()->getName();

78) How to create model controller and migration in a single artisan command in Laravel?


php artisan make:model ModelNameEnter -mcr

79) How to use Where null and Where not null eloquent query in Laravel?

Where Null Query

DB::table('users')->whereNull('name')->get();

Where Not Null Query

DB::table('users')->whereNotNull('name')->get();

80) How many types of joins does Laravel have?

  • Inner Join
  • Left Join
  • Right Join
  • Cross Join
  • Advanced Join
  • Sub-Query Joins

81) How to use joins in laravel?

Laravel supports various joins that’s are given below:-

Inner Join

DB::table('admin') ->join('contacts', 'admin.id', '=', 'contacts.user_id') ->join('orders', 'admin.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price') ->get();

Left Join / Right Join

$users = DB::table('admin') ->leftJoin('posts', 'admin.id', '=', 'posts.admin_id') ->get();
$users = DB::table('admin') ->rightJoin('posts', 'admin.id', '=', 'posts.admin_id') ->get();

Cross Join

$user = DB::table('sizes') ->crossJoin('colours') ->get();

Advanced Join

DB::table('admin') ->join('contacts', function ($join) { $join->on('admin.id', '=', 'contacts.admin_id')->orOn(…); }) ->get();

Sub-Query Joins

$admin = DB::table('admin') ->joinSub($latestPosts, 'latest_posts', function ($join) { $join->on('admin.id', '=', 'latest_posts.admin_id'); })->get();

82) How to get current action name in Laravel?

request()->route()->getActionMethod()

83) What is Blade laravel?

Blade is very simple and powerful templating engine that is provided with Laravel. Laravel uses “Blade Template Engine”.

84) How to check Ajax request in Laravel?

You can use the following syntax to check ajax request in laravel.

1
2
3
if ($request->ajax()) {
     // Now you can write your code here.
}

85) What are string and array helpers functions in laravel?

Laravel includes a number of global “helper” string and array functions. These are given below:-

Laravel Array Helper functions

  • Arr::add()
  • Arr::has()
  • Arr::last()
  • Arr::only()
  • Arr::pluck()
  • Arr::prepend() etc


Laravel String Helper functions

  • Str::after()
  • Str::before()
  • Str::camel()
  • Str::contains()
  • Str::endsWith()
  • Str::containsAll() etc

86) How To Enable The Query Logging?

DB::connection()->enableQueryLog();

87) List out Databases Laravel supports?

Currently Laravel supports four major databases, they are :-

  • MySQL
  • Postgres
  • SQLite
  • SQL Server

88) How to use cookies in laravel?

How to set Cookie?
 To set cookie value, we have to use Cookie::put('key', 'value');

How to get Cookie?

 To get cookie Value we have to use Cookie::get('key');

How to delete or remove Cookie?

 To remove cookie Value we have to use Cookie::forget('key')

How to check Cookie?

 To Check cookie is exists or not, we have to use Cache::has('key')

 

 

 

 

No comments:

Post a Comment