Laravel Interview Questions
Laravel Interview Questions
© Copyright by Interviewbit
Contents
2. Define Composer.
Composer is the package manager for the framework. It helps in adding new
packages from the huge community into your laravel application.
For example, one of the most used packages for authentication will be Passport, for
including that into your project, you can run the below command on your terminal:
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"require": {
"php": "^7.3|^8.0",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.12",
"laravel/tinker": "^2.5"
},
"require-dev": {
"facade/ignition": "^2.5",
"fakerphp/faker": "^1.9.1",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.2",
"nunomaduro/collision": "^5.0",
"phpunit/phpunit": "^9.3.3"
}
}
The “require” and “require-dev” keys in composer.json specify production and dev
packages and their version constraints respectively.
PostgreSQL
SQL Server
SQLite
MySQL
5. What is an artisan?
Artisan is the command-line tool for Laravel to help the developer build the
application. You can enter the below command to get all the available commands:
PHP artisan list: Artisan command can help in creating the files using the make
command. Some of the useful make commands are listed below:
php artisan make:controller - Make Controller file
php artisan make:model - Make a Model file
php artisan make:migration - Make Migration file
php artisan make:seeder - Make Seeder file
php artisan make:factory - Make Factory file
php artisan make:policy - Make Policy file
php artisan make:command - Make a new artisan command
Laravel is the best choice to make progressive, scalable full-stack web applications.
Full-stack web applications can have a backend in laravel and the frontend can be
made using blade files or SPAs using Vue.js as it is provided by default. But it can also
be used to just provide rest APIs to a SPA application.
Hence, Laravel can be used to make full-stack applications or just the backend APIs
only.
And can put the application again on live using the below command:
php artisan up
Each migration file is stored with its timestamp of creation to keep track of the order
in which it was created. As migrations go up with your code in GitHub, GitLab, etc,
whenever anyone clones your project they can run `PHP artisan migrate` to run
those migrations to create the database in their environment. A normal migration
file looks like below:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
The up() method runs when we run `php artisan migrate` and down() method runs
when we run `php artisan migrate:rollback`.
If we rollback, it only rolls back the previously run migration.
If we want to rollback all migrations, we can run 'php artisan migrate:reset`.
If we want to rollback and run migrations, we can run `PHP artisan migrate:refresh`,
and we can use `PHP artisan migrate:fresh` to drop the tables first and then run
migrations from the start.
<?php
use App\Models\Auth\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
The run() method in the above code snippet will create 10 new users using the User
factory.
Factories will be explained in the next question.
Factories are a way to put values in fields of a particular model automatically. Like,
for testing when we add multiple fake records in the database, we can use factories
to generate a class for each model and put data in fields accordingly. Every new
laravel application comes with database/factories/UserFactory.php which looks like
below:
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'
'remember_token' => Str::random(10),
];
}
}
The above command will create a new factory class for the User model. It is just a
class that extends the base Factory class and makes use of the Faker class to generate
fake data for each column. With the combination of factory and seeders, we can
easily add fake data into the database for testing purposes.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use SoftDeletes;
// ...
}
This will create a file in the models’ directory and will look like below:
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [];
}
A Model can have properties like table, fillable, hidden, etc which defines properties
of the table and model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
The above method phone on the User model can be called like : `$user->phone` or
`$user->phone()->where(...)->get()`.
We can also define One to Many relationships like below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
Since a user can have multiple addresses, we can define a One to Many relations
between the User and Address model. Now if we call `$user->addresses`, eloquent
will make the join between tables and it will return the result.
Eloquent is the ORM used to interact with the database using Model classes. It gives
handy methods on class objects to make a query on the database.
It can directly be used to retrieve data from any table and run any raw query. But in
conjunction with Models, we can make use of its various methods and also make use
of relationships and attributes defined on the model.
Some examples of using the Eloquent are below:
`DB::table(‘users’)->get()`
`User::all()`
`User::where(‘name’, ‘=’, ‘Eloquent’)->get()`
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
Route::get('/user', function () {
//
});
});
This will enable the /user route to be accessed by a particular user from a particular
IP only 60 times in a minute.
Facades in Laravel
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserLoggedIn
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* The user instance.
*
* @var \App\Models\User
*/
public $user;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
}
For this event to work, we need to create a listener as well. We can create a listener
like this:
php artisan make:listener SetLogInFile --event=UserLoggedIn
The below resultant listener class will be responsible to handle when the
UserLoggedIn event is triggered.
use App\Events\UserLoggedIn;
class SetLogInFile
{
/**
* Handle the given event.
*
* @param \App\Events\UserLoggedIn
* @return void
*/
public function handle(UserLoggedIn $event)
{
//
}
}
When any request is submitted to a laravel route, it goes through to the controller
method, and with the help of dependency Injection, the request object is available
within the method. We can do all kinds of things with the request like validating or
authorizing the request, etc.
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
Route::get('/profile/{id}', 'UserController@profile');
In the UserController profile method, the reason we can get the User model as a
parameter is because of Service Container as the IoC resolves all the dependencies in
all the controllers while booting the server. This process is also called route-model
binding.
use Illuminate\Support\Facades\Route;
Route::get('/home', function () {
return 'Welcome to Home Sweet Home';
});
A typical closure route looks like the above, where we provide the URI and the closure
function to execute when that route is accessed.
Route::get('/hello', 'HomeController@index');
Another way is like above, we can directly give the controller name and the method
to call, this can again be resolved using Service Container.
Route::get('/hello', 'HomeController@index')->name('index');
return redirect()->route('index');
Route::middleware(['throttleMiddleware'])->group(function () {
Route::get('/', function () {
// Uses throttleMiddleware
});
Route::get('/user/profile', function () {
// Uses throttleMiddleware
});
});
The above command will create a new middleware file in the app/Http/Middleware
folder.
Route::resource('blogs', BlogController::class);
This will create routes for six actions index, create, store, show, edit, update and
delete.
The Laravel Service Container or IoC resolves all of the dependencies in all
controllers. So we can type-hint any dependency in controller methods or
constructors. The dependency in methods will be resolved and injected in the
method, this injection of resolved classes is called dependency Injection.
Laravel Contracts
Few examples of contracts in Laravel are Queue and Mailer. Queue contract has an
implementation of Queuing jobs while Mailer contract has an implementation to
send emails.
What the above code will do is it will give another attribute(full_name) in the
collection of the model, so if we need the combined name we can call it like this:
`$user->full_name`. Mutators are a way to do some operations on a particular field
before saving it to the database.
For example, if we wanted the first name to be capitalized before saving it to the
database, we can create something like the below:
$user->first_name = Input::get('first_name');
$user->save();
It will change the first_name to be capitalized and it will save to the database.
Conclusion
Laravel is the most used PHP framework for web development. Laravel interviews
consist of questions about a deep understanding of PHP MVC architecture and app
development basics like routes, controllers, views, and advanced topics such as
Service Container, Dependency Injection, Accessors & Mutators, etc.
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions