Top Laravel Interview Questions & Answers
Click
⭐ if you like the project. Pull Request are highly appreciated.
Table of Contents
When a user enters a URL or call a console command etc, it gets send to a routes folder. web.php route is for web requests while api.php route is for API requests.
Below is an example get route from routes/web.php
. You can call website.com/foo and it will bring the result.
Route::get('foo', function () {
return 'Hello World';
});
There are four types of routes,
A. web.php
B. api.php
C. console.php
D. broadcast.php
-
What is web php?
web.php used for web routes. Like example.com/test
Route::get('/test', function () { $path = storage_path() . "/app/json/options/docs.json"; return view('skin/dev-wireframe', array('menu' => json_decode(file_get_contents($path), true))); });
-
What is api php?
The place where we write API route for mobile and API usage. Like http://localhost:8080/api/test
Route::get('/test', function () { $path = storage_path() . "/app/json/options/docs.json"; return view('skin/dev-wireframe', array('menu' => json_decode(file_get_contents($path), true))); });
-
What is channels php?
It is used for broadcasting
-
What is Controller?
Controller is the place where we write the logic of the program. Placed in app/Http/Conrollers
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; class UserController extends Controller { /** * Show the profile for the given user. * * @param int $id * @return Response */ public function showProfile($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }
-
What are Views?
Views is the fornt end of Laravel. Stored in resources/views
.
```
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
```
-
What is a Model?
A model is where you write the database logic. Stored in
/app
-
What is Request-Response?
When we type a URL, a request is sent to the server. The server goes from /public to bootstrap folder from which is goes to the routes file. The route files sends it the right controller/view.
When we access via any of the 4 ways,
- write a url
- write a console command
- do a broadcast
- hit an api
the request goes to index.php (which usually is in the /public folder or the root folder). From there, the request goes to bootstrap folder, then to the Auth rules and after that lands in the routes folder in any of the web, api, console or the broadcast routes which is dependant on which route you called.
-
What are Migrations?
Migrations help us keep SQL tables in code. When we have to setup the DB, we just run the migration.
-
What are Service Providers?
Service providers are responsible for booting and configuration (binding all resources.)
-
What is Middleware?
Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism.
-
What is ORM?
Object oriented and Model based way of accessing DB. The ORM Laravel uses is Active Records.
-
What is Eloquent?
The ORM wrapper Laravel uses is called active records. The active record that is used is Eloquent. Every table has a model associated with it.
A database wrapper that makes it easy to access DB.
-
What are Facades?
Facades are used to hide implementation details and complexities from end user making him/her feel like interacting with a black box.
-
What is Repository Pattern?
Repository pattern is used to create templates where implementation details are left to be implemented in child classes. It helps with further expansion of code and avoid bottlenecks in class updation.
-
What is Authentication using Passport?
Passport uses OAuth making it a more secure choice for authentication. The details are taken care of by Passport.
Break the function into separate unit so it can be tested individually.
-
What is Caching?
Configured using
config/cache.php
. Used for database caching. Popular ways Redis and Memcache.
-
What are Queues?
Queue is a line of jobs to be proccessed. You can create multiple queues which is multiple lines of jobs
We use PHP Mailer. The config of SMTP are given in .env.
Error handling is managing exception
in a Laravel application. Laravel uses App\Exception\Handler for it.
Use api.php. Link will be x.com/api/slug
You can do event based programming in Laravel that is attach stuff to when an event happens. You can do that via events.
-
What are Payments and cashier?
Payment processing is difficult. Cashier is a package which makes it easy. Its installed using composer.
-
What is Package development?
Laravel uses composer which gets packages. You can develop your own package and submit.
https://laravel.com/docs/5.8/scout
Add the entry to config/database.php
-
What is Single Page Application in Laravel?
There is single URL. The assets are loaded once and only content keeps changing using JSON request. Its not great for SEO but there are workarounds to create virtual URL.
-
What are Microservices in Laravel?
There are many services which are similar sized. Each performs exactly one function and they talk to each other.
-
What is CSRF and JWT token?
CSRF and JWT tokens are used to make sure the action is performed by the user. If there is no token, someone can give a link to user to click or hide it behind some action and him do what the hacker wants. A JWT token is hidden in the request while CSRF token is not.
-
What is Service Oriented Architecture in Laravel?
There are many services which are similar sized. Each performs exactly one function and they talk to each other.
-
What are Validations and custom validations?
Validations are used to make sure input is of the kind function wanted. Custom validators are custom made valiators.
-
What is Route caching?
Caching of routes to make going to routes faster. Command:
php artisan route:cache
-
What is Dependency injection in Laravel?
Laravel injects dependencies as function parameters. Read more: https://medium.com/a-young-devoloper/how-laravel-injects-our-dependencies-14e1b1a044e
They provide insstructions to interact with a facade.
https://laravel.com/docs/7.x/contracts
You can enable logging queries and Laravel will record the queries which were run.
-
What are Laravel Traits?
They solve diamond problem which is when you have to inherit from two classes.
-
What are System requirements for Laravel?
PHP version, MySQL, PHP packages mentioned on Laravel.com, apache server
$price = DB::table('orders')->max('price');
To generate the process of generating the URL which leads to a route. Its used in MVC apps. You can use it using named routes in laravel.
-
List some artisan commands
php artisan list php artisan make:migrate php artisan make:controller php artisan make:model php artisan config:clear php artisan serve
-
What is Current version of PHP MySQL Laravel MongoDB etc?
PHP: PHP 7.4 MySQL: 7 Laravel: 6 MongoDB: 4
-
Describe design architecture of an app?
There are three layers
- Presentation layer: Front end
- Business layer: Backend and logic
- Data layer: Model and database
-
What are SQL Injections?
Its a hacking trick used to complete a SQL query by filling a form content and placing query parts inside the form.
-
What is Abstract class?
A class which is just a template i.e has no defination but just declaration.
-
Explain Unions
Union vertically joins tables together i.e the records are added into the same columns.
-
How mongodb is better than relational databases?
It is faster and it stores data in JSON form so you can enter multiple types of data without being dependent on the data being consistent in type.
It is a NO SQL key value based database.
2 hours.
-
How to create hooks in Laravel?
https://stackoverflow.com/questions/36226021/hooks-in-laravel-5
CSRF and JWT tokens are used to make sure the action is performed by the user. If there is no token, someone can give a link to user to click or hide it behind some action and him do what the hacker wants.
-
Select highest and nth highest salary from DB
SELECT name, salary FROM #Employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2 WHERE e2.salary > e1.salary)
https://javarevisited.blogspot.com/2016/01/4-ways-to-find-nth-highest-salary-in.html
-
Write a union
SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] UNION [DISTINCT] SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions];
Like a 3 tables joined.
Uber's DB arcitecture.
-
What is the difference between GET and POST
GET is used for retriving data POST is used to perform a change i.e action
-
Which is fast between GET and POST?
GET is used for retriving data POST is used to perform a change i.e action
-
Explain 4 basics of OOP
Inheritance Polymorphism Encapsulation Abstraction
-
What is MVC Framework?
It provides separation of concerns by separating the code into 3 parts,
- Model: Database logic
- View: Frontend logic
- Controller: Backend logic
-
In MySql we use many types of engines which one is faster and why?
There are two main types of engines, 1.InnoDB 2.MyISAM InnoDB is faster.
`DB::unprepared()` is used for it.
```
php artisan make:migration create_trigger
```
Stored procedures are SQL code in tables. It is called and executed inside tables.
PHP 7.4 brings,
1.
2.
Cookies is data sent with every request. It is usually generalized for all. Session is data related to a specific user.
```
array_unique(array_merge($array1,$array2), SORT_REGULAR);
```
$str="Find the count of vowel and consonants"
$i=0; $vowel=0; $const=0;
foreach ($char in $str)
{
if(($char==" ") || ($i==0))
{
if(($str[$i+1]==a) || ($str[$i+1]==e) || ($str[$i+1]==i) || ($str[$i+1]==o) || ($str[$i+1]==u))
$vowel++;
else
$const++;
}
$i++;
}
AWS has 20 main categories and 150 sub-categories of items. For hosting, EC2 is a well known server type.
Composer has built in packages for it. They may get stopped due to IP usage (no of connections
In require, you can use require multiple times for the same file. It will add the file multiple times while require_once will only require it once.
In include() the script will run even if the file is not found while in require it will stop if file required is not found.
```
/bootsrtrap
/public
/routes
/resources
/config
/app
.env
```
etc
```
composer create-project --prefer-dist laravel/laravel blog "5.8.*"
```
Eloquent
One To One
One To Many
One To Many (Inverse)
Many To Many
Has Many Through
Polymorphic Relationships
One To One
One To Many
Many To Many
Custom Polymorphic Types
```
php artisan down
```
dd() is dump and die. It prints the variable/array and exits the script.
Inside `config/app.php`
```
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
...
```
Common function which you can use in many classes are stored in helper functions.
Which can be mass assigned.
Which can't be mass assigned.
a closure gives you access to an outer function's scope from an inner function
```
$user = auth()->user();
print_r($user);
```
Used for compiling JS.
Used for compiling JS.
-
List out databases that laravel supports?
Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server.
By mentoning the name of the table in `$table` variable
QB: $users = DB::table('users')->select('name', 'email as user_email')->get();
Eloquent: $users = User::all();
https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
https://laravel.com/docs/5.2/errors
Helps with logging.
https://laravel.com/docs/5.8/eloquent-serialization
When we make a request , we get a responsse.
https://laravel.com/docs/5.8/responses#response-macros
https://www.cloudways.com/blog/laravel-and-api-rate-limiting/
https://laravel.com/docs/5.8/eloquent-relationships
https://stackoverflow.com/questions/14935846/laravel-4-how-can-i-get-the-environment-value
$table=""
https://stackoverflow.com/questions/49348681/what-is-a-usage-and-purpose-of-laravels-binding
https://stackoverflow.com/questions/25229064/laravel-difference-appbind-and-appsingleton
https://stackoverflow.com/questions/40767040/how-laravels-container-binding-mechanisms-differ
https://stackoverflow.com/questions/40767040/how-laravels-container-binding-mechanisms-differ
https://stackoverflow.com/questions/40767040/how-laravels-container-binding-mechanisms-differ
Giving your binding a name.
-
Explain Extending Bindings?
https://stackoverflow.com/questions/40767040/how-laravels-container-binding-mechanisms-differ
Makes controller, view, route, group and other items in artisan.
php artisan cache:cleaer
Virtual box for vagrant
Request::ip();
https://tutsforweb.com/creating-helpers-laravel/
-
How can we create a record in Laravel using eloquent?
$flight = new Flight; $flight->name = $request->name; $flight->save();
Request::ip();
A design pattern which masks SQL queries to make database CRUD operations easy.
insert() only inserts
insertGetId() inserts and returns id of last added item
https://vapor.laravel.com/
Major version . Minor version . Bug fix
Jobs:
Middleware:
It uses Blade Templating Engine
https://laravel-news.com/eloquent-subquery-enhancements
https://fullstackworld.com/post/what-is-new-to-laravel-6
https://laravel.com/docs/6.x/collections#lazy-collection-introduction
https://medium.com/@panjeh/laravel-define-global-constants-config-php-file-5d6a9900bb6e
-
How to remove /public from URL in laravel?
Rename server.php in your Laravel root folder to index.php Copy the .htaccess file from /public directory to your Laravel root folder.
-
What are the difference between soft delete & delete in Laravel?
https://blog.hashvel.com/posts/eloquent-orm-soft-delete-permanent-delete-in-laravel/
Using `Form` class.
```
<html>
<body>
<?php
echo Form::open(array('url' => '/uploadfile','files'=>'true'));
echo 'Select the file to upload.';
echo Form::file('image');
echo Form::submit('Upload File');
echo Form::close();
?>
</body>
</html>
```
Make a controller to loop through all pages and list them. Make a route to it.
https://www.bestinterviewquestion.com/question/how-to-use-skip-take-in-laravel-query-kcle83908l2
Tinker is command line code functionality where you can write Laravel code in CLI.
https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop
Use it as an array in a single or function.
Use it as an array inside where function.
SELECT that column and chekc if result is not null
https://medium.com/@sdkcodes/laravel-eloquent-eager-loading-9596b15e8b5d
php artisan key:generate
LTS version is a version where the support is longer i.e it gets longer fixes and support and is a stable version.
https://www.bestinterviewquestion.com/question/how-to-use-group-concat-with-join-in-laravel-cht1n5023bz
Change the minutes in config\session.php file.
@extends('name.app')
Package that manages user permissions
https://stackoverflow.com/questions/29231587/laravel-check-if-ajax-request
dd($Request)
https://laravel.com/docs/5.8/helpers
https://laravel.com/docs/5.8/helpers
https://stackoverflow.com/questions/48062083/laravel-5-4-exclude-a-route-with-parameters-from-csrf-verification
https://laravel.com/docs/5.7/authorization#policy-methods
Run migration rollback. If you want to rollback more than one steps, give the steps count.
https://laravel.com/docs/5.8/dusk
Used with broadcasting and sockets.
Identifies a code block and treats it separate fropm the rest so same name confusions don't occur.
Laravel managed cloud hosting
CodeIgniter is an older framework and Laravel is a much advanced framework.
https://codebriefly.com/brief-understanding-on-laravel-observers/
Laravel starts from there.
120 minutes
It is used for creating API. Its url is /api/slug
https://laravel.com/docs/5.7/hashing
https://medium.com/@nedsoft/laravel-localization-made-simple-8ee4a34731e7
Pass it from the routes. To add for all views: https://laravel.com/docs/5.7/views#sharing-data-with-all-views
Enter a route. It will go to the routes file to match the route and return a response.
-
I just have installed a fresh version of Laravel 5, and I have the white screen of death. What’s wrong?
You might see the white screen of death because of not enough permissions in folders. Try changing permissions of `/public`, `/vendor`, `/storage` folders.
```
public function __construct() {
$this->middleware(function ($request, $next) {
$name = session()->get('businessinfo.name'); // get value from session
View::share('user_name', $name); // set value for all View
View::share('user_email', session()->get('businessinfo.email'));
return $next($request);
});
}
```
Create it in the .env file
See `composer.json` file.
It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
Laravel dependencies. Their code.
Convert variables to array.
...
/public /bootstrap/cache /vendor
php artisan --version
https://blog.vanila.io/why-laravel-is-best-php-framework-98a2784d76dc?gi=a81f8fa92a65
Service container is like a container where we define how the dependency should be resolved. We have to register the dependencies into the service container during the initialization of the framework and the best place to do it is the service provider.
CREATE:
$flight = new Flight;
READ:
$flights = App\Flight::all();
foreach ($flights as $flight) {
echo $flight->name;
}
UPDATE:
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
DELETE:
$flight->delete();
CREATE:
DB::table('users')->insert( ['email' => '[email protected]', 'votes' => 0] );
READ:
$users = DB::table('users')->get();
UPDATE:
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
DELETE:
DB::table('users')->where('votes', '>', 100)->delete();
source: https://laravel.com/docs/5.8/queries
A way to get all of the data of a one or more models which might be required.
--
-
What are the day to day tasks of a Laravel developer?
- Creating APIs
- Write queries using Eloquent
- Write helper functions
- Installing required extensions for setting up Laravel
- Setting up docker
- Setting up homestead
- Vue
- Writing complex queries using eloquent
- Using design patterns to build scaleable solutions
- Tweak blade template.
- Create SPA
- Seed data into the database --
Two ways,
- Turn the DB logs on and check the last query run in it.
- add ->ToSQL() function after the query.
Create a helper.php file anywhere and place the functions in it
Add its location in the composer.json files
area.
Run composer dump autoload
Answer here: https://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-in-laravel-5
web: run phpinfo() function
cli: php -m
Use a single where clause and give the parameters as array
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
There are 4 cache in Laravel. Clear them all.
php artisan key:generate
php artisan config:cache
php artisan cache:clear
php artisan view:clear
php artisan route:clear
Where is used for rows, having is used for columns.
We can protect site from SQL injections by sanitizing inputs. Whenever you have to enter string, use PHP function mysqli_real_escape_string().
For XSS protection i.e when you have to enter string in HTML use htmlspecialchars.
You should always try to use use prepared statements.
make:cast Create a new custom Eloquent cast class
make:channel Create a new channel class
make:command Create a new Artisan command
make:component Create a new view component class
make:controller Create a new controller class
make:event Create a new event class
make:exception Create a new custom exception class
make:factory Create a new model factory
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:notification Create a new notification class
make:observer Create a new observer class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:resource Create a new resource
make:rule Create a new validation rule
make:seeder Create a new seeder class
make:test Create a new test class
POST, GET, PUT, PATCH, and DELETE etc
$users = DB::table('users')->paginate(15);
Object–relational mapping is used to use Object oriented way to use database.
- What are pub/sub in Laravel?
Its a broadcasting method. Pub=Publisher Sub=Subscriber Decreases communication complexity Peforms its task without knowing the other details of the system