Laravel Interview Questions | Basic
Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern.
Laravel Interview Questions | Installation
For Other Info Please Check Laravel Official Website
You may also like - PHP OOPS Interview Questions
- Lumen is a micro-framework provided by Laravel.
- It is developed by creator of Laravel Taylor Otwell.
- It is mostly used for creating RESTful API’s & microservices.
- Lumen is built on top components of Laravel.
Composer is PHP dependency manager used for installing dependencies of PHP applications.
- 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.
- To view a list of all available Artisan commands, you may use the list command:
- To view a list of all available Artisan commands, you may use the list command:
- Mostly used Artisan commands are:
Reasons why Laravel is the best PHP framework:
- Artisan - A Command-Line Interface
- Migrations & Seeding
- Blade Template Engine
- Middleware - HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
- Eloquent ORM + Built-in Database Query Builder
- Routing (RESTful routing)
- Inbuilt packages - Authentication, Cashier, Scheduler, SSH, Socialite
- Unit Testing - Built-in unit testing and simply readable impressive syntax
- Caching - Laravel provides an expressive, unified API for various caching backends
Read more in detail about these
Following are some official packages provided by Laravel:
Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box.
- In Short, Laravel provides Passport for API Authentication.
- Laravel Passport is an OAuth2 server and API authentication package that is simple to use
Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services
- 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.
- 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.
You may also like - Core PHP Interview Questions
By default Laravel is configured to use MySQL.
In order to change your default database edit your config/database.php
ORM: Object-relational Mapping (ORM) is a programming technique that help in converting data between incompatible type systems into object-oriented programming languages.
You may also like - Node.js Interview Questions and Answers
Eloquent ORM is being used by Laravel.
- Each database table has a corresponding "Model" which is used to interact with that table.
- Models allow you to query for data in your tables, as well as insert new records into the table.
- All Eloquent models extend Illuminate\Database\Eloquent\Model class
The easiest way to create a model instance is using the make:model artisan command
Now look following Example:
Eloquent will assume the User model stores records in the users table
You may specify a custom table by defining a table property in your model, like below:
- Eloquent relationships are defined as methods on your Eloquent model classes
- Relationships supported by Laravel Eloquent ORM:
- One To One - hasOne
- One To Many - hasMany
- One To Many(Inverse) - belongsTo
- Many To Many - belongsToMany
- Has Many Through - hasManyThrough
- Polymorphic Relations
- Many To Many Polymorphic Relations
Blade is the simple, yet powerful templating engine provided with Laravel.
Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views
In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application
Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.
Visit official website of Laravel for more details
You can enable maintenance mode in Laravel, simply by executing below command.
dd() – Stands for "Dump and Die"
Laravel's dd() is a helper function ,which will dump a variable's contents to the browser and halt further script execution.
Middleware provide a convenient mechanism for filtering all HTTP requests entering in your application.
The Laravel Service Container is a powerful tool for managing class dependencies and performing dependency injection.
Dependency injection is technique which means: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.
Almost all of your service container bindings will be registered within service providers
- More Reusable Code
- More Testable Code
- More Readable Code
- Service Providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.
- Bootstrapping mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
- All service providers extend the Illuminate\Support\ServiceProvider class.
- Most service providers contain a register and a boot method.
- Within the register method, you should only bind things into the service container.
In Short, Facades provide a "static" interface to classes that are available in the application's service container.
All of Laravel's facades are defined in the Illuminate\Support\Facades namespace.
Facades have many benefits. They provide a short and memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually.
Facades Vs Helper Functions: There is absolutely no practical difference between facades and helper functions. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:
You may also like - RESTful APIs Interview Questions
- Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application
- Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.
- Don't worry if you don't see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.
- A single event can have multiple listeners that do not depend on each other.
In eloquent ORM, $fillable is an array which contains all those fields of table which can be filled using mass-assignment.
Mass assignment, means to send an array to the model to directly create a new record in Database
Guarded is the reverse of fillable.
If fillable specifies which fields to be mass assigned, guarded specifies which fields are not mass assignable.
If you want to block all fields from being mass-assign you can just do this.
$fillable serves as a "white list", $guarded functions like a black list. you should use either $fillable or $guarded.
A Closure is an anonymous function. Closures are often used as a callback methods and can be used as a parameter in a function.
- Laravel's Contracts are a set of interfaces that define the core services provided by the framework.
- For example, a Illuminate\Contracts\Queue\Queue contract defines the methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed for sending e-mail
- Each contract has a corresponding implementation provided by the framework.
As of PHP 5.4, we now have a mechanism for reusing code, called Traits.
The laravel Auth Facade is used to get the autheticated user data as
Laravel can optionally log in memory all queries that have been run for the current request
You may also like - MongoDB Interview Questions
- Yes, Laravel supports popular caching mechanism like Memcached and Redis.
- By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system.
- For large projects it is recommended to use Memcached or Redis.
Currently, Laravel supports four databases:
- SQL Server
We can use custom table in Laravel by simply overriding protected $table property of Eloquent.
You may also like - MySQL Interview Questions
Laravel is a development framework and, as such, it won't make your server more secure, just your application. Laravel features allow you to use everything securely. All the data is sanitized where needed unless you're using Laravel with raw queries.
Laravel accessors and mutators are custom, user defined methods that allow you to format Eloquent attributes.
- Accessors:Accessors are used to format attributes when you retrieve them from the database
- Mutators:Mutators are used to format attributes before saving them into the database
By default, Laravel is configured to create a log file for your application in the storage/logs directory.
Log files are in storage/logs/laravel.log, laravel.log is the default filename.
You may write information to the logs using the Log facade
The logger provides the eight logging levels defined in RFC 5424: emergency, alert, critical, error, warning, notice, info and debug.
you can visit official website to read in more detail
Laravel utilizes the Monolog library, which provides support for a variety of powerful log handlers.
Laravel is written in PHP.
In Laravel exceptions are handled by App\Exceptions\Handler class.
This class contains two methods:
In RESTful APIs, sometime you need to convert your models and relationships to arrays or JSON. this can be done using methods provided by Eloquent.
Convert into Array:
Convert into JSON:
Laravel Interview Questions | Response
All Routes and Controllers should return a response to be sent back to the user's browser.
Laravel provides several different ways to return responses:
- View Responses
- JSON Responses
- File Downloads
- File Responses
- Response Macros
- Redirecting To Named Routes
- Redirecting To Controller Actions
- Redirecting To External Domains
- Redirecting With Flashed Session Data
If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade
Rate Limit, means sometime you need to retrict access of routes within your application.
Rate Limit can be implemented in Laravel using Throttle Middleware.
The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes.
For example, let's specify that an authenticated user may access the following group of routes 60 times per minute:
If required, you can make it dynamic using model's attribute (e.g. - in our case suppose it's - rate_limit).
You may also like - React.js Interview Questions
Laravel Eloquent ORM provides two type of loading.
- Lazy Loading: By default, accessing data in eloquent is "Lazy loaded"
- Eager Loading: This can be achieved using with() in Eloquent. Eager loading alleviates the N + 1 query problem.
$environment = App::environment();
Laravel Interview Questions | Features of Laravel 5.8
Laravel 5.8 is now released and has many improvements, addition and some breaking changes.
- Caching TTL
- Deprecated Helper Functions
- Dotenv 3.0
- Carbon version 2
- Notifications Package
- Testing PHPUnit 8
- Password Length
- Error Page
- Artisan Call Improvements
- Email Validation
- Eloquent Resource Key Preservation
- Higher Order orWhere Eloquent Method
- JSON in MYSQL
- Correct Pluralisation
- Mock / Spy Testing Helper Methods
- Artisan Serve Improvements
- Auto-Discovery Of Model Policies
- HasOneThrough Relationship
- Token Guard Token Hashing
- Default Scheduler Timezone
- Multiple Broadcast Authentication Guards