What do you know about Laravel?
Laravel is a one of the most popular and widely used opensource web framework based on PHP. It is a web application framework with expressive, elegant syntax. It is designed to make developing web apps easier and faster through built-in features. It is developed by Taylor Otwell and the first version of Laravel was released on 9th June 2011.
Laravel supports the MVC (Model-View-Controller) architectural pattern and provides an expressive and elegant syntax, which is useful for creating a wonderful web application easily and quickly.
What are the new features in Laravel 8?
Laravel 8, the most recent version of the Laravel framework released on 8th Sep 2020 with the latest and unique features.
- Migration Squashing
- Job Batching
- Rate limiting improvements
- Maintenance mode improvements
- Pre-Rendering the Maintenance Mode View
- Catch improvements
- Dynamic Blade components
- Event listener improvements
- Time testing helpers
- Artisan serve Improvements
- Routing Namespace Updates
Why Laravel?
Laravel is one of most popular frameworks and it is open-source latest web application framework that used for designing customized web applications easily and quickly.
- Artisan is the command line interface in the Laravel. Provides a number of commands while developing a web application
- A lightweight Blade Templating Engine
- Automated features like Cross-Site Request Forgery (CSRF) protection, Validation, Migrations
- Larger Community catering to thousands of programming geeks and application developers Elegant and expressive syntax.
- Elegant Dependency Injection
- Inbuilt Unit Testing and Authentication System and Paginations
- Laravel offers different API for various caching system
- Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir, Passport, Laravel Scout.
- Eloquent ORM with PHP active record implementation.
- Responsible Interface
- Laravel UI and Laravel Spark for web/mobile apps
- Responsible Interface.
- High Security
- Easy to understand Laravel Documentation
Can you explain the features of Laravel framework?
Some Features of Laravel framework:
Template engine: Laravel Frame is highly recognized for its built-in lightweight templates that help you create stunning designs by seeding dynamic content. In addition to this, it has multiple widgets that incorporate CSS and JS code with solid structures. The Laravel framework templates are innovatively designed to create a simple design with distinctive sections.
Bundles: These are small packages which you may download to add certain functionality to your web application. Hence, saving a lot of coding stuff and time. These may be containing some custom functionality.
Unit testing: It is an important part of Laravel framework. It runs hundreds of tests to ensure that new changes don’t unexpectedly break anything. Laravel is widely considered to have some of the most stable releases in the industry as it is cautious of the known failures. Slowly it is being liked by the developers. It also makes it easy to write unit-tests for own code. One can then run tests with the “Artisan” command-line utility.
Eloquent ORM (Object-Relational Mapping): Laravel framework offers the Eloquent ORM that includes a simple PHP Active Record implementation. It lets the web app developers issue database queries with PHP syntax rather than writing SQL code. Every table in the database possesses a corresponding Model through which the developer interacts with said table. An ORM is relatively faster than all other PHP frameworks.
Routing system: In this framework takes an incredibly simple and easy-to-use approach to routing. Most beginner PHP developers aren’t familiar with anything other than the most natural of route systems. It brings more flexibility and control over which route is triggered on the application. A directory is created to match any desired URI.
Restful Controllers: Rest controllers are an optional way to separate your GET and POST request logic. In a login example your controller’s get_login () action would serve up the form and your controller’s post_login() action would accept the posted form, validate, and either redirect to the login form with an error message or redirect your user to their dashboard.
Libraries & Modular: Laravel is also popular due to its Object-Oriented libraries as well as many other pre-installed libraries. These pre-installed libraries are not found in any other PHP frameworks. One of the preinstalled libraries is an Authentication library which is easy-to-implement and has many latest features, such as checking active users, Bcrypt hashing, password reset, CSRF (Cross-site Request Forgery) protection, and encryption. Furthermore, this framework is divided into individual modules that adopt modern PHP principles allowing developers to build responsive, modular, and handy web apps.
Monolog logging library:
Database migration system: It provides you with the service of changing database structure and helps to modify it by using PHP code instead of SQL. Laravel Schema Builder helps to create database tables & insert indices.
Security: Application security is one of the most important concerns in web application development. At the time of developing an application, each programmer has to use some effective ways to make it secure. Laravel handles the security of web applications within its own framework. It uses the hashed and salted password meaning that the password would never save as plain text in a database. It also uses “Bcrypt Hashing Algorithm” for generating an encrypted representation of a password. In addition, this PHP web development framework uses prepared SQL statements which makes injection attacks unimaginable.
URL Touting Configuration:
Can you explain the use of event in Laravel?
An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel’s events provides a simple observer implementation, allowing you to subscribe and listen for various events/actions that occur in your application. The classes of events are generally stored in the Events or app directory, on the other hand, listeners are kept in either app or Listeners.
Some events examples in Laravel
- A new user is registered
- A new comment is posted
- A new product is added
Can you explain validations in Laravel and how it is used?
Validations are approaches that Laravel use to validate the incoming data within the application. Laravel provides many ways to validate your data. 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.
Laravel validation Example
$validatedData = $request->validate([
'name' => 'required|max:255',
'username' => 'required|alpha_num',
'age' => 'required|numeric',
]);
List of all available validation rules and their function Here @ See more
Can you explain PHP artisan and Name some common artisan commands?
Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. We can run these commands according to our need. To view a list of all available Artisan commands, you may use the list command:
php artisan list
Here is the list of some artisan commands
-
php artisan list;
-
php artisan –version
-
php artisan down;
-
php artisan help;
-
php artisan up;
-
php artisan make:controller;
-
php artisan make:mail;
-
php artisan make:model;
-
php artisan make:migration;
-
php artisan make:middleware;
-
php artisan make:auth;
-
php artisan make:provider etc.;
Can you explain database migration and How to create migration via artisan?
Migrations are like version control for your database, it allows us to modify and share the application’s database schema easily. Migrations are typically paired with Laravel’s schema builder to build your application’s database schema.
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.
To create a migration, use the make:migration Artisan command:
php artisan make:migration create_users_table
The new migration will be placed in your database/migration’s directory.
What is CSRF protection and how to disabled?
By default, CSRF (Cross-Site Request Forgery) is on with Laravel and resides in “app/Http/Middleware/VerifyCsrfToken.php”. The CRSF help to protect your website from malicious attacks. You can disable CSRF by writing some code into VerifyCsrfToken.php file.
What are service providers and How will you register?
Service providers are the central place of all Laravel application bootstrapping. Your application, as well as all of Laravel’s core services are bootstrapped via service providers. All service providers are registered in the config/app.php configuration file.
To create a service provider, I will use the below-mentioned artisan command.
php artisan make: provider ClientsServiceProvider
To register your provider, add it to the array:
'providers' => [
// Other Service Providers
App\Providers\ComposerServiceProvider::class,
],
Most of the service providers contain below-listed functions in its file:
- Register() Function
- Boot() Function
What do you know about Laravel Service Container?
Service container is a powerful tool for managing class dependencies and performing dependency injection in Laravel. It is also known as IoC container.
Pro of Service Container:
- Ability to manage class dependencies on object creation
- Ability to bind of interfaces to concrete classes
- Using the Service Container as a Registry
Can you explain Composer and installation process of it?
Composer is a tool for managing dependency in PHP. It manages the dependencies which are required for a project.
Laravel Installation Steps:
- Download composer from https://getcomposer.org/download
- Open command prompt
- Go to htdocs folder
- Run command under C:\xampp\htdocs>composer create-project laravel/laravel projectname
If you need to install particular version, then you need to mention the version after projectname, if you didn’t mention any particular version, then it will install with the latest version.
Can you explain the dependency injection and their types?
Dependency injection is a powerful, useful, and critical technique to use in order to write clean, loosely coupled, easy to maintain code. There are three ways to do dependency injection, each having its own use case.
There are three types of dependency injection:
- Constructor Injection: In this type of injection, the injector supplies dependency through the client class constructor.
- Property Injection: In this type of injection, the injector method injects the dependency to the setter method exposed by the client.
- Interface Injection: In this type of injection, the injector uses Interface to provide dependency to the client class. The clients must implement an interface that will expose a setter method which accepts the dependency.
Can you Explain the concept of contracts in Laravel?
Laravel’s Contracts are a set of interfaces that define the core services provided by the framework. All of the Laravel contracts live in their own GitHub repository.
Learn more about Contracts like When to use and How to use @ See more..
Can you explain Facades and how it can be used in Laravel?
Facades provide a static interface to classes that are available in the application’s service container. They serve as static proxies for underlying classes present in the service container, offering benefit of expressive syntax while maintaining more flexibility and testability than other available traditional static methods.
All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.
You can easily access a facade like so:
use Illuminate\Support\Facades\Cache;
Route::get('/cache', function () {
return Cache::get(' PutkeyNameHere');
});
Learn more about Facades like When to use and How to use @ See more..
Can you explain Laravel Eloquent and Various types of relationships are available?
Eloquent is an ORM used in Laravel. It provides a beautiful, simple Active Record implementation working with your database. Each database table has a corresponding Model which is used to interact with that table.
We can create Eloquent models using the make:model command.
Types of relationship in Laravel Eloquent are:
- One to One relationship
- One to Many relationships
- Many to Many relationships
- Has Many Through relationships
- Polymorphic relationships
- Many to Many Polymorphic relationships
Learn more about Laravel Eloquent @ See more..
How will you enable the query log in Laravel?
You can use enableQueryLog method to enable query log in Laravel.
My first step will be
DB::connection()->enableQueryLog();
After that query, should be placed
$querieslog = DB::getQueryLog();
After that, it should be placed
dd($querieslog)
Example
DB::connection()->enableQueryLog();
$result = User:where(['status' => 1])->get();
$log = DB::getQueryLog();
dd($log);
Can you tell me some aggregates methods of query builder?
Some of the methods that Query Builder provides are:
- count() – Usage:$products = DB::table(‘products’)->count();
- max() – Usage:$price = DB::table(‘orders’)->max(‘price’);
- min() – Usage:$price = DB::table(‘orders’)->min(‘price’);
- avg() – Usage:$price = DB::table(‘orders’)->avg(‘price’);
- sum() – Usage: $price = DB::table(‘orders’)->sum(‘price’);
What do you know about Reverse routing?
Reverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible.
Example:
Route::get(‘login’, ‘users@login’);
Using reverse routing we can create a link to it and pass in any parameters that we have defined. Optional parameters, if not supplied, are removed from the generated link.
{{ HTML::link_to_action('users@login') }}
Can you explain about Traits in Laravel?
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. Traits are generated to reduce the limitations of single inheritance in PHP and it were introduced in PHP in version 5.4 and are used extensively in the Laravel Framework.
Can you explain middleware in Laravel?
In Laravel, Middleware acts as a middleman between request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.
There are two types of Middleware in Laravel.
- Global Middleware: It will run on every HTTP request of the application.
- Route Middleware: It will be assigned to a specific route.
Example
// Syntax
php artisan make:middleware MiddelwareName
// Example
php artisan make:middleware UserMiddelware
Now UserMiddelware.php file will create in app/Http/Middleware
Learn more about Middleware @ See more..
Can you explain about Lumen?
Lumen is a micro-framework built on Laravel’s top components. It is a smaller, and faster, version of a building Laravel based services, and REST API’s. It 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.
You can install Lumen using composer by running below command
composer create-project --prefer-dist laravel/lumen blog
For More:
Can you explain about bundles?
In Laravel, bundles are also called packages. Packages are the primary way of adding 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.
Learn more about Package Development @ See more..
How will you check request is ajax or not?
I can use $request->ajax() method to check request is ajax or not.
Example:
public function index(Request $request)
{
if($request->ajax()){
return response()->json(['status'=>'Ajax request']);
}
return response()->json(['status'=>'Http request']);
}
Can you explain about Vapor?
Laravel Vapor is an auto-scaling, serverless deployment platform for Laravel, powered by AWS Lambda. It used to manage Laravel Infrastructure with the scalability and simplicity of serverless.
Does Laravel support caching?
Yes, Laravel supports caching of popular backends such as Memcached and Redis.
How you will delete or clear caching in Laravel?
I will use below commands to clear Cache in Laravel.
php artisan config:clear
php artisan cache:clear
Can you name the databases supported by Laravel?
Laravel supports four databases:
What’s the default database type in Laravel and How you can change it?
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', 'postgresql')
By using it, MySQL changes to PostgreSQL.
Can you explain about PHP artisan and Some of Commands of it?
Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application.
Few artisan commands listed below:
php artisan list – To view a list of all available Artisan commands
php artisan –version – To Know the current version of your Laravel
php artisan migrate –env=local – To specify the configuration environment
Learn more about Artisan @ Se more..
What’s the significant difference between delete() and softDeletes()?
delete(): remove all record from the database table where as softDeletes(): does not remove the data from the table. It is used to flag any record as deleted.
What do you know about Laravel Dusk?
Laravel Dusk is a tool which is used for testing JavaScript enabled applications. It provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine.
Learn more about Laravel Dusk @ See more..
Can you Explain homestead in Laravel?
Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. If something goes wrong, you can destroy and re-create the box in minutes!
What are Bundles, Reverse Routing and The IOC container?
Bundles: A bundle can have its own views, configuration, routes, migrations, tasks, and more. A bundle could be everything from a database ORM to a robust authentication system. These are small functionality which you may download to add to your web application.
Reverse Routing: Its reverse-routing is generating URLs based on route declarations. This allows you to change your routes and application will update all of the relevant links as per this link.
IOC container: The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.
What is the use of csrf_token() function?
csrf_token() function can be used in the meta tag and the hidden input field of the HTML form. It generates a random string as a CSRF token.
What is the use of csrf_field() function?
csrf_field() function creates a hidden field for the HTML form where it is used and generates CSRF token.
How will you get the user's IP address in Laravel?
We can get the user’s IP address using:
public function getUserIp(Request $request){
// Gettingip address of remote user
return $user_ip_address=$request->ip();
}
How will you get client IP address in Laravel?
We can get the client IP address using:
Request::ip();
How you can use the custom table in Laravel?
We can easily use custom table in Laravel by overriding protected $table property of Eloquent. Here, is the sample:
class User extends Eloquent{
protected $table="my_user_table";
}
How will you check the logged-in user info?
User() function is used to get the logged-in user
Example
if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}
How will you extend the login expire time in Auth?
We can extend the login expire time with config\session.php this file location. Just update lifetime the value of the variable. By default, it is ‘lifetime’ => 120. According to your requirement update this variable.
Example
'lifetime' => 180
How will you the get data between two dates?
we can use whereBetween() function to get data between two dates.
Example
Users::whereBetween('created_at', [$firstDate, $secondDate])->get();
What are the various joins in Laravel?
Inner Join
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
Left Join / Right Join
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
$users = DB::table('users')
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
Cross Join
$sizes = DB::table('sizes')
->crossJoin('colors')
->get();
Advanced Join
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
Subquery Joins
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
How will you check table is exists or not in our database using Laravel?
We can use hasTable() to check table exists in our database or not.
Syntax
Schema::hasTable('users'); // here users is the table name.
Example
if(Schema::hasTable('users')) {
// table is exists
} else {
// table is not exists
}
How will you generate application key in Laravel?
We can use php artisan key:generate to generate your application key. The key will be written automatically in .env file.
If we want to see the key after generation we can use –show option php artisan key:generate –show
How will you get user details by ID?
public function getUserById(Request $request){
$id =$request->input('id');
$user = User::find($id);
return $user;
}
How will you get user details by email?
public function getUserByEmail(Request $request){
$email =$request->input('email');
$user = User::where('email',$email)->first();
return $user;
}
How to add Helper file in Laravel?
First, to create custom helpers.php file in laravel
After, we need to edit composer.json file in laravel.
In autoload object add the following file array: -
"autoload": {
"files": [
"app/helpers.php"
]
},
Run the command:
composer dump-autoload
This will create a helpers.php file in your app folder. Which will be accessed by all controllers and view files.
Best way to add a function in your Helper file is to check if it already exists or not
<php
if (! function_exists('your_custom_helper')) {
function your_custom_helper($string) {
// your code
}
}
How to bypass CSRF Token for A Route in Laravel?
Laravel CSRF token is security tokens but sometimes we don’t need them in our request URLs.
Edit Only One file for this called VerifyCsrfToken.php.
URL Path:- /app/Http/Middleware/VerifyCsrfToken.php
Add Below Code In The Class:-
protected $except = [
'api/*', //For All Route starting with api.
' Insert your_url_here/', //For Specific url.
];
How to merge Collection in Laravel?
To merge two collection coll1 and coll2 we use merge () method of collection
$collection = collect ();
$collection->merge (['col1' => $coll1, 'coll2' => $coll2 ]);
OR
We can just pass those collection while declaring the collection
$collection = collect([
'coll1' => $coll1,
'coll2' => $coll2
]);
How to create a record in Laravel using eloquent?
To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage
public function saveProduct(Request $request )
$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();
What are the differences between Laravel vs CodeIgniter?
Laravel:
- Laravel is a framework with expressive, elegant syntax.
- Laravel community is still small, but it is growing very fast.
- Development is enjoyable, creative experience
- Exceptions with detailed stack trace.
- Laravel5 is built for latest version of PHP
- Support for database platforms including MySQL, PostgreSQL, and SQLServer.
- It is more object oriented compared to CodeIgniter
- Unit testing support.
- Inbuilt CLI support
Codeigniter:
- CodeIgniter is a powerful PHP framework
- Codeigniter community is large.
- Simple and elegant toolkit to create full-featured web applications.
- Codeigniter doesn’t have exceptions
- Codeigniter is an older more mature framework
- It is less object oriented compared to Laravel.
- Don’t inbuilt CLI support