Laravel: Interview Questions and Answers

Here are the questions that you might get in an interview about Laravel. The questions are divided into sections, so you can jump to any specific section if you want to.

General

What is Laravel?

Laravel is an open source framework for web appliation in PHP. It follows MVC (Model-View-Controller) architectural pattern.

What is Artisan in Laravel?

Artisan is a command-line interface(CLI) that comes with Laravel, to help us with development and other task, like- generating files, migrations, managing queue, and much more.

Artisan is powerd by Symfony Console.

Developers can extend its functionality by defining/creating custom commands.

How do you use environment variables in Laravel?

Environment variables are saved in .env file. Variables are saved in the key=value format like below-
APP_NAME=BigBoxCode
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=bbcode
DB_USERNAME=root
DB_PASSWORD=root*secret


We can retrieve these values directly using env("KEY_NAME_HERE") function.
But it is better not to use the env() function directly in the code, as the configuration caching in production can cause issue. It is better to use the env() in config file and use the value from config in your code using config() function.

Read this article for more details of the issue and best practiceLaravel: env() getting null value when used with config:cache

Use the following command to cache the configuration(in production):
php artisan config:cache

Clear config cache using:
php artisan config:clear

For production environment we need to make sure that the following 2 values are changed-
APP_ENV=production
APP_DEBUG=false


Check current environment using command-
php artisan env

Check config value using following command-
php artisan config:show app.name

Lastly, the automated testing command( php artisan test ) will automatically use the values from file .env.testing , and if the value is not present in .env.testing then it will fall back to .env file.

Directory & Files

What is the role of the `config` directory in Laravel’s architecture?

The config directory is used to manage configuration setting in an application.
It contains files for the setting values for different parts of the application, such as general app values, datbase, email, caching, file system, queue, etc.

each config file returns an array, where the values can be obtained from .env, or some other setting can be set. Here is an example-
<?php
// config/app.php
return [
    'name' => env('APP_NAME', 'Laravel'),
    'env' => env('APP_ENV', 'production'),
    'debug' => (bool) env('APP_DEBUG', false),
    'url' => env('APP_URL', 'http://localhost'),
    'timezone' => 'UTC',
    'locale' => env('APP_LOCALE', 'en'),
    // Other settings here
];


We can get the values in any part of our code by using the config() function.
Pass the file name and setting name, separated by dot(.), like below-
$appName = config("app.name");
$databaseName = config("database.connections.mysql.database");


We can pass a default value to config(), as fallback/default value-
$appName = config("app.name", "SomeDefaultAppName");
$databaseName = config("database.connections.mysql.database", "default_db");

What is the purpose of the `bootstrap` folder in Laravel?

Here are the key points of the “bootstrap” directory-

This directory includes “bootstrap/app.php” file, which is used to initialize the app and load essential services before handling requests.
Contains “bootstrap/providers.php” file to list of service providers that are required for running the application.
Contains “cache” directory for optimized configuration packages, services and route caching, to improve performance.

How does Laravel’s Blade templating engine fit into the overall architecture?

Blade templating engine helps to build the “view” layer of MVC in Laravel. Here are the key points of blade-

Makes it really easy to build the UI layer.
Organize the view by combining other blade files or components using directives @extends, @section, @yeild, @include, @component, etc.
Provides directives for conditional and loops, like @if, @else, @for, @foreach, etc.
Provides a way to print variables passed from controllers, ie. {{ $myVar }}.

What is the purpose of `app/Providers/AppServiceProvider.php` in Laravel?

app/Providers/AppServiceProvider.php file in Laravel is the default service provider that is loaded when the application starts.
Its primary purpose is to bootstrap the application by registering services, bindings, and performing any setup that is required at the beginning of the application’s lifecycle.

The AppServiceProvider class extends the ServiceProvider class, and contains 2 methods-
register() : used to register services to service container. This is where we bind classes, interfaces, or services to the container, to make it available for dependency injection.
boot(): contains tasks that need to happen after all services are registered, for example, event listeners, model bind, view composers.

Controllers & Requests

How do you create a new controller in Laravel?

Create a controller using the following command:
php artisan make:controller YourControllerName

For example, if we want to create controller for Customers, we name our controller CustomerController. So, use the following command:
php artisan make:controller CustomerController

Create a resource controller which contains method for CRUD operations – index, create, store, edit, update, destroy, by using --resource flag:
php artisan make:controller CustomreController --resource

Use the --api flag to create API controllers:
php artisan make:controller CustomerController --api


After creating the controller, we need to create the methods to the route file(routes/web.php or routes/api.php), to specify which method is responsible for handling which URL endpoint.

How do you validate form requests in Laravel?


Inline Validation: Use the “validate” method from the Request object, and pass the validation rules as array-
class CustomerController extends Controller {
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:customers,email',
'phone' => 'nullable|digits:10',
]);
Customer::create($validatedData); return redirect()->back()->with('success', 'Customer created successfully.');

}
}


Form Request Validation: for large request, like form requests we can create a request using following command-
php artisan make:request StoreCustomerRequest

Then in the rules() method we can define our rules-
class StoreCustomerRequest extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:customers,email',
'phone' => 'nullable|digits:10', ];
}
public function messages() {
return [ ];
}
}


We can define custom error message in the messages() method.

Routing

Which files are used to define routes in Laravel?

Use the files in routes/ directory to define route. Here is what file to choose for what purpose-
routes/web.php – for web routes, for browser based requests.
routes/api.php – for API routes, which by default has prefix /api.
routes/console.php – for artisan console commands.
routes/channels.php – for broadcasting channels.

How to define a route in Laravel?

Here is how we can define route simply in the route file-
Route::get('/customers', function () {
$customers = Customer::all();
return response()->json($customers);
});


Here is how to define routes with controllers-
Route::get('/customers', [CustomerController::class, 'index']);
Route::post('/customers', [CustomerController::class, 'store']);

How to define routes with parameters (required and/or optional)?

Set the param in route inside curly braces. For example, if we want to pass “id” to the customer route-
Route::get('/customers/{id}', [CustomerController::class, 'show']);

Add a question mark(?) to the parameter name to make it optional-
Route::get('/customers/{id?}', [CustomerController::class, 'show']);

What are named routes in Laravel?

Use the name function to define name for a route definition-
Route::get('/customer/{id}', [CustomerController::class, 'show'])->name('customer.profile');

Then we can use it to redirect to that route-
return redirect()->route('customer.profile', ['id' => 1]);

To get the URL use the route() method-
$url = route('customer.profile', ['id' => 1]);

Or link like this-
<a href="{{ route('customer.profile', ['id' => 1]) }}">Profile</a>

Check if the current route matches this profile route-
if (request()->routeIs('customer.profile')) {
// Do something
}

How to define grouped routes(with prefix and middleware)?

Use the prefix() function to set the prefix.
Use middleware() function to set middlewares.
Finally use the group function to group the routes.

Here is an example-
Route::prefix('admin')->middleware(['auth'])->group(function () {
Route::get('/dashboard', [AdminController::class, 'dashboard']);
Route::get('/profile', [ProfileController::class, 'profile']);
Route::get('/settings', [SettingController::class, 'settings']);
});

What is resource route and how to do define one?

A resource route automatically generates controller methods for CRUD operations-
Route::resource('customers', CustomerController::class);

Here are the routes and controller methods, that a resource route generates-
GET /customersindex()
GET /customers/createcreate()
GET /customers/{customer}show()
POST /customersstore()
GET /customers/{customer}/editedit()
PUT/PATCH /customers/{customer}update()
DELETE /customers/{id}destroy()

What are route model bindings, and how do they work in Laravel’s architecture?

Route model binding is the process where we can automatically inject model instance through route parameter, into our controller methods.

Define the following in route-
Route::get('/customers/{customer}', [CustomerController::class, 'show']);

Define it in the controller-
class CustomerController extends Controller {
public function show(Customer $customer) {
return view('customer.show', compact('customer'));
}
}


We call the URL-
https://bigboxcode.com/customers/1

Here is how the binding works-

Automatic Binding: Laravel automatic binds a route param to a model, based on the model name. This will automatically resolve to Customer model instance, identified by the primary key(id).

Explicit Binding: We can explicitely define which binding should resolve to which model. Add this to any service provider, in your AppServiceProvider, or create a new service provider RouteServiceProvider

public function boot()
{
parent::boot();

Route::model('customer', \App\Models\CustomCustomer::class);
}


This binds the ‘customer‘ from the route to the model “CustomerCustomer“.

Custom Binding: We can define custom binding, say we want to fetch “Post” by “slug“, then we have to define the route as below-
Route::get('/post/{slug}', [PostController::class, 'show']);

Then defien the custom binding in your AppServiceProvider, or your custom RouteServiceProvider
public function boot() {
parent::boot();

Route::bind('post', function ($slug) {
return Post::where('slug', $slug)->firstOrFail();
});
}

Middleware

What is middleware in Laravel?

Middleware stays between an incoming request and application response.
It is used to filter and/or modify and/or restrict access to a certain route before the request reaches the controller.

Here are common usage of Laravel middleware-
Authentication – check if user is loggedin or not.
Authorization – check if the user(or role) has permission to access the resource.
CSRF Protection – validate a Cross-Site Request Forgery attempt.
Logging – tract the user or request activity.
CORS Handling – managing Cross-Origin Resource Sharing.
Request Modification – modify incoming request before it reaches to the controller.
Response Modification – modify outgoing request after the controller finished processing, and response being sent to the user.

How do you create a middleware in Laravel?

Generate a middleware using artisan command-
php artisan make:middleware CheckUserRole

This will create a middleware file, and we can write our middleware logic inside the CheckUserRole.php –
class CheckUserRole
{
public function handle(Request $request, Closure $next): Response
{
if (!$request->user() || $request->user()->role !== 'admin') {
return redirect('/home');
}
return $next($request);
}

How do you register middleware in Laravel?

If it is a global middleware then register it in bootstra/app.php file, inside withMiddleware()
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(CheckUserRole::class);
})


For applying a middleware to a route use the middleware() function-
Route::get('/', function () {
// ...
})->middleware([CheckUserRole::class]);

What is the difference between global middleware and route middleware?

Global Middleware: global middlewares are applicable to all request, and automatically run on every request to any route of the application.
Route Middleware: a route middleware only applies to the specific route.

How do you pass parameters to middleware?

We can pass the parameter while applying the middleware to route-
Route::get(‘/premium-content’, [ContentController::class, ‘premiumContent’])->middleware(‘subscription:premium,18’);

Then we can accept the values in the handle() method like below-
public function handle(Request $request, Closure $next, $subscriptionType, $ageRequirement) {
$user = $request->user();

if (!$user || $user->subscription_type !== $subscriptionType || $user->age < $ageRequirement) {
return redirect('/home');
}

return $next($request);
}

What is the difference between before middleware and after middleware?

Before Middleware: before middlewares are executed before the request reaches to the controller.
class CheckIfAuthenticated {
public function handle($request, Closure $next) {
if (!auth()->check()) {
return redirect('/login');
}

return $next($request);
}
}


After Middleware: after middlewares are executed after the controller finish processing the request, and return the response.
class AddCustomHeader {
public function handle($request, Closure $next) {
$response = $next($request);
$response->headers->set('X-Custom-Header', 'Big Box Head');

return $response;
}
}

What is throttle middleware, and how do you use it?

Throttle middleware is a builtin middleware in Laravel, that is used to limit the number of request by a client, in a certain time period.
Route::get('/customers', [CustomerController::class, 'index'])->middleware('throttle:60,1');

This allows 60 requests to the /customers endpoint in 1 minute.

If the limit exceeds then user gets-
Response Status: 429
Message: { “message”: “Too many requests.” }

Every time a request comes, Laravel saves the request count in cache(whatever cache driver you have set).
We can define our custom throttle middlewire.

How do you handle middleware priority in Laravel?

Set priority of middleware in the withMiddleware method in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->priority([
\App\Http\Middleware\CheckAuth::class,
\Illuminate\Auth\Middleware\CustomHeader::class,
]);
})


In this case the CheckAuth middleware will be executed first, then CustomHeader.

How do you implement role-based access control (RBAC) using middleware?

If we have multiple roles like, admin, manager, etc. and we want to give access to certain route to certain role-
Route::get('/admin', [AdminController::class, 'index'])->middleware('role:admin');
Route::get('/shop', [ShopController::class, 'index'])->middleware('role:manager');
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('role:admin,manager');


Here is the definition of the of the handle method of the middleware-
public function handle(Request $request, Closure $next, …$roles) {
if (!Auth::check() || !in_array(Auth::user()->role, $roles)) {
abort(403, 'Unauthorized');
}

return $next($request);
}

What is terminable middleware, and how do you use it?

A terminable middleware that has a terminate() method in it, and this terminate method is executed after the request is sent to user.

This type of middleware would have 2 methods-
handle() – which is executed before request is sent to the user.
terminate() – which is executed after the request is sent to the user.

These terminate() method is used to tasks like logging, background processing and/or cleanup, etc.

Here is an example-
class SomeCustomMiddleware {
public function handle(Request $request, Closure $next) {
return $next($request);
}

public function terminate($request, $response) {
Log::info('Response sent to user- ', [ 'url' => $request->fullUrl(), 'status' => $response->status(), ]);
}
}

Database

Migration

What is database migration in Laravel?

Database migration in Laravel work as version control for changes in database schema. We can save the database schema changes in PHP code.

We can also apply the changes in a migrations and revert the changes with simple artisan commands.

How do you create a migration in Laravel?

Use artisan command make:migration to create a migration-
php artisan make:migration create_customer_table

This will create a file in the database/migrations/ directory.

If needed, use -m flag to create migration, while creating the model.
php artisan make:model Customer -m

The migration file has a class with 2 methods-
up() – for applying the changes in database, when we run the migration.
down() – for reverting the changes when we want to rollback(the changes done in the up method).

Here is a sample migration file-
return new class extends Migration {
public function up(): void {
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down(): void {
Schema::dropIfExists('customers');
}
};

How to run a migration?

Use the artisan command migrate to run the migration-
php artisan migrate

This will execute the up() method of the migration(s). This will run all the pending migrations.

Laravel saves the information of which migrations are already executed in the migrations table in database.

How to rollback migration?

To revert the changes done by a migration, use the artisan command migrate:rollback
php artisan migrate:rollback

This will run the down() method of the migration(s).

To rollback specific number of migrations use the –step flag-
php artisan migrate:rollback --step=3

How to refresh the database?

Use the migrate:refresh command to rerun all the migrations-
php artisan migrate:refresh

This will drop all tables and re-run all the migrations.

To run seeder along with database migration refresh use the –seed flag-
php artisan migrate:refresh --seed

What is the purpose of foreignId() in Laravel migrations?

The foreignId() function is used establish the foreign key relationship in databases. This foreignId() is a shortcut to set id as foreign key-
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained();
$table->timestamps();
});


This use of foreignId() is equivalent to –
$table->foreign('customer_id')->references('id')->on('customers');

How do you manage and track migrations in a large Laravel application?

If there are lots of migration files, then we can split those in separate directories, like, user, customer, product, or any other logical groups.
the migrate command will run all migration from database/migrations and all it’s subdirectories.

If needed check the status of migration using migrate:status command-
php artisan migrate:status

If you want to check what queries will run in the next migration, without running the migration, us the –pretend flag –
php artisan migrate --pretend

Use the following command to create a schema file-
php artisan schema:dump

This will create a schema file in database/schema directory. And, next time you run the migration, it will take the schema from that schema file(the migration files will be ignored in that case). Using this schema will reduce the migrations time, in case of large migration.

Seeder

What is a database seeder, and why do we use it?

Seeder is a class in Laravel, that is used to insert initial data or some dummy/test data into the database.

Use cases-
Initial data – add initial data set, like a user, admin user, customer, etc..
Dummy data – add dummy data for the development environment.
Config data – data set for configuration, like, country, city, customer type, order status, user role, permission, etc.
Test data – add date while running tests, to verify different operations.

How to create a database seeder?

Use artisan command make:seeder to create seeder-
php artisan make:seeder CustomerSeeder

This creates a file database/seeders/CustomerSeeder.php. This file extends Seeder and implements a run() function-
class CustomerSeeder extends Seeder {
public function run() {
// Creates a single record
Customer::create([
'name' => 'First User',
'email' => 'user1@bigboxcode.com',
]);

// Creates 10 random records
Customer::factory(10)->create();
}
}


This seeder is not executed by default, when we run the seeder command.

We need to register the seeder in the file database/seeders/DatabaseSeeder.php, in the run() method –
public function run() {
$this->call([
CustomerSeeder::class,
ProductSeeder::class,
OrderSeeder::class,
]);
}


All these registered seeders will be executed, when we run the artisan command db:seed.

How to run a seeder?

Run the seeders by using the artisan command db:seed:
php artisan db:seed

We can run the seeders while running the migrations, use the –seed flag:
php artisan migrate --seed

These commands will run all the seeders registered in database/seeders/DatabaseSeeder.php.

If we want to run a specific seeder then use –class flag like below-
php artisan db:seed --class=CustomerSeeder

How do we conditionally seed data?

We can add condition like below-

Check count and add rows if there is no entry-
public function run() {
if (Customer::count() == 0) {
Customer::factory(10)->create();
}
}


Use the firstOrCreate to add record with condition-
public function run() {
Customer::firstOrCreate(
['email' => 'user1@bigboxcode.com'],
['name' => 'First User']
);
}


Check environment if environment is ‘local‘ or ‘testing‘ –
public function run() {
if (App::environment('local', 'testing')) {
Customer::factory(10)->create();
}
}


Check if admin exist, and add new admin if there is none-
public function run() {
if (!User::where('role', 'admin')->exists()) {
User::create([
'name' => 'Admin User',
'email' => 'admin@bigboxcode.com',
'role' => 'admin',
'password' => bcrypt('password'),
]);
}
}

Should we use seeder in production?

Certain seeders need to run in production-
For adding configurations, like, user roles, country, city list, etc.
For adding default users, or some other values like this.

For everything else we like dummy data, we should add a checking for the environment, and add dummy data only for development environment.

Factory

What is factory in Laravel, and what are the use cases?

Factory is feature in Laravel that allows us to generated dummy/fake data for database tables.
Factory uses Faker library to generate random data, and these dummy data are useful for development, and/or testing.

How does factory differ from seeder?

Faker is used to insert dummy/fake/random data to database.

But, seeder is used to insert specific data to database. Sometimes we use factory inside seeder, with the intention to insert fake data.

How to create a factory?

Use artisan command make:factory to create a factory, also set the model for that factory by using –model flag-
php artisan make:factory CustomerFactory --model=Customer

This will create a factory file database/factories/CustomerFactory.php, and we can define how the factory data will be generate-
class CustomerFactory extends Factory {
protected $model = Customer::class;
public function definition(): array {
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'phone' => $this->faker->phoneNumber,
'address' => $this->faker->address,
];
}
}

How to use a factory in seeder?

To enable the factory support for the Customer model, make sure that it uses the HasFactory trait-
class Customer extends Model {
use HasFactory;
}


Then we can use the factory anywhere we want-
Customer::factory()->count(10)->create();

Like in a seeder we can use-
class CustomerSeeder extends Seeder {
public function run() {
Customer::factory(50)->create();
}
}

How do you define relationships in factories to create related data?

Say we have 2 models, Order and Customer. Make sure the relation is defined in the model.
Then define the factories like below-
class CustomerFactory extends Factory {
protected $model = Customer::class;
public function definition(): array {
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
}


Then in the order factory create customer along with the order-
class OrderFactory extends Factory {
protected $model = Order::class;
public function definition(): array {
return [
'customer_id' => Customer::factory(),
'order_number' => $this->faker->uuid,
'total' => $this->faker->randomFloat(2, 10, 500),
];
}
}

What is Faker, and how does Laravel use it in factories?

Faker is a PHP library for generating fake data for testing and development. This package is used to generate random data, like, names, emails, address, phone number, etc.

Can you use a factory without inserting data into the database?

Yes, we can use factory to just generate data and return it, without inserting it to database.

Define a factory-
class CustomerFactory extends Factory {
protected $model = Customer::class;
public function definition(): array {
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
}


Now use the make method to create data and return it-
$customer = Customer::factory()->make();
dd($customer);


or-
$customers = Customer::factory()->count(10)->make();
dd($customers);

Eloquent ORM

What is Eloquent in Laravel?

Eloquent is the ORM(Object-Relation Mapper) shipped with Laravel. It provides an easy way to interact with the database.
Here are the key features of eloquent-
⇾ Active Record Pattern- each model represents a table from the database.
Expressive API– it has very easy and expressive for querying and other database operations.
Relationships – supports many relationships like one-to-one, one-to-many, many-to-many, hasManyThrough, etc.

There are many more features that Eloquent supports.

What is a model in Laravel, and how to define one?

A model is Laravel represents a table in Laravel. And each object of the model, represents a record/row from the table.

Use the command make:model to create a model-
php artisan make:model Customer

This will create file app/models/Customer.php. This is how the model definition looks like-
class Customer extends Model {
use HasFactory;

protected $table = 'customers';
protected $fillable = ['name', 'email', 'phone'];
public $timestamps = true;
}

How do you retrieve all records from a table using Eloquent?

Use the all() function of the model-
$customers = Customer::all();

What is the difference between `get()`, `first()`, and `find()` in Eloquent?

get() is for getting all records-
$customers = Customer::where('status', 'active')->get();

first() is for getting the first record record that matches the condition-
$customer = Customer::where('status', 'active')->first();

find() is for getting single record based on primary key-
$customer = Customer::find(10);

How do you insert a record using Eloquent?

Use the create() method of the model-
$customer = Customer::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'status' => 'active',
]);

How do you update a record using Eloquent?

$customer = Customer::find(1);
$customer->update([
'name' => 'Updated Name',
'status' => 'active',
]);

How do you delete a record using Eloquent?

Find the record and delete-
$customer = Customer::find(1);
if ($customer) {
$customer->delete();
}


Use destroy() to delete by id-
Customer::destroy(1);

or pass array of ids-
Customer::destroy([2, 3, 4]);

Delete with where clause-
Customer::where('status', 'inactive')->delete();

How to delete record and related/dependent record?

Without auto-cascade-
$customer = Customer::find(1);
if ($customer) {
$customer->orders()->delete();
$customer->delete();
}


With auto-cascade, use the deleting event of database model, to auto delete related records-
class Customer extends Model {
protected static function boot() {
parent::boot();
static::deleting(function ($customer) {
$customer->orders()->delete(); });
}

public function orders() {
return $this->hasMany(Order::class);
}
}

How do you define timestamps in an Eloquent model?

Use the timestamps() method to add the timestamp related column to a table-
public function up(){
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}


Using the $table->timestamps() will add columns “created_at” and “updated_at”. These columns are managed and updated by Laravel by default.

To disalbe timestamp for a model, use $timestamps = false, in the model-

class Customer extends Model {
public $timestamps = false;
}

What is soft delete, and how do we use soft deletes in Laravel?

Soft delete allows you to delete a record without permanently removing it from the database. In this case, Laravel sets the “deleted_at” timestamp, which is used to determine if the record is deleted or not.

Add the soft delete option to the migration to add the deleted at column-
public function up(){
Schema::table('customers', function (Blueprint $table) {
$table->softDeletes(); // Adds deleted_at column
});
}


Use the SoftDeletes trait on a model to enable soft delete.
use Illuminate\Database\Eloquent\SoftDeletes;
class Customer extends Model {
use SoftDeletes;
}


In any case if you want to get the deleted record, then use withTrashed() like below-
Customer::withTrashed()->find(1);

Use the restore() method to restore a soft deleted record-
$model->restore();

To force delete from database, use forceDelete()-
$model->forceDelete();

What is the purpose of the `$fillable` property in Eloquent?

$fillable property is an allowlist (whitelist) that defines which attributes can be mass assigned.

class Customer extends Model {
protected $fillable = ['name', 'email', 'address'];
}

What is the purpose of the `$guarded` property in Eloquent?

$guarded property is a blocklist (blacklist) that defines which attributes cannot be mass assigned-
class Customer extends Model {
protected $guarded = ['role'];
}


The “role” property will be ignored if provided in the model create.

How do you order query results in Eloquent?

How do you paginate query results in Laravel?

How do you use raw SQL queries in Laravel?

What is the difference between Eloquent and Query Builder?

How does Laravel’s Eloquent ORM work internally?

How do you use the exists() and count() methods in Eloquent?

How do you dynamically filter query results using request parameters in Eloquent?

How do you use Laravel’s upsert functionality?

How do you use casting in an Eloquent model?

How do you use stored procedures in Laravel?

How do you prevent mass assignment vulnerabilities in Laravel?

How do you define a custom accessor in Eloquent?

How do you define a custom mutator in Eloquent?

How do you implement query scopes in Eloquent?

What is the purpose of the touches property in Eloquent?

How do you use the when() method in Eloquent queries?

Eloquent Relationship

How do you define a database relationship in Eloquent?

What is the difference between `hasOne()` and `belongsTo()`?

What is the difference between hasManyThrough() and hasOneThrough() in Laravel?

How do you implement complex relationships in Eloquent?

What is the difference between `has()` and `with()` in Eloquent queries?

What is lazy loading in Eloquent, and why should you avoid it in some cases?

What is eager loading, and how does it improve performance?

How do you implement complex relationships using `morphMap()` in Laravel?

What is the difference between `join()` and `leftJoin()` in Laravel Query Builder?

What is the hasManyThrough() relationship in Eloquent?

How does the belongsToMany() relationship work in Eloquent?

What is polymorphic relationships in Laravel?

How do you implement a many-to-many polymorphic relationship in Eloquent?

Query Builder

What is Laravel Query Builder?

Laravel query builder is an API provided by the Laravel framework, that we can use to interact with the database, in a fluent and expressive way.
We can use the query builder and query the database, without writing raw SQL queries.
Provides an easy-to-use, chainable interface for writing queries.
Automatically escapes parameters, to prevent SQL injection.

What is the difference between Eloquent ORM and Query Builder?

Eloquent ORM:
Uses Active Record pattern.
Imphesise on models(object to represent data), and relation between models(for database table relations).

Query Builder:
Uses Fluent Interface pattern.
Use it when we want to build complex queries without a model, when performance and flexibility are the priority.

Give an example Laravel Query Builder?

$users = DB::table('users')
->where('age', '>', 18)
->where('name', 'BigBoxCode')
->join('posts', 'users.id', '=', 'posts.user_id')
->select('users.name', 'users.email', 'posts.title')
->orderBy('users.name')
->limit(10)
->get();

Transactions

How do you handle database transactions in Laravel?

How does Laravel handle database transactions within its architecture?

How do you handle concurrent database updates in Laravel?  

Observer

What are model observers in Laravel?

What are the benefits of using database events in Laravel?

Query Optimization

How do you index database columns efficiently in Laravel?

How does Laravel handle the N+1 query problem, and how can you optimize queries?

How do you use the chunk() method in Eloquent for handling large datasets?

How do you use job batching with database queues in Laravel?

Authentication & Authorization

How does Laravel’s authentication system work?  

What are Laravel guards and providers in authentication?  

How do you implement role-based access control (RBAC) in Laravel?  

How do you customize Laravel’s default authentication system?  

What is Passport and Sanctum in Laravel, and when should you use them?  

How does Laravel handle API authentication with Sanctum?  

What is policy-based authorization in Laravel?  

What are Laravel policies and gates?

What is Laravel Passport and how does it work?

What is Laravel Sanctum and how is it different from Passport?

How do you handle rate limiting in Laravel?

Sessions & Storage

How do you store session data in Laravel?  

Development & Execution

What is the difference between `php artisan serve` and running Laravel on a local web server?  

Architecture

Model-View-Controller(MVC)

Explain the MVC architecture in Laravel.  

How does Laravel follow the MVC architecture?  

Design Patterns

Explain the repository pattern in Laravel.

What is the Repository Pattern, and how is it used in Laravel applications?

How does Laravel implement the Chain of Responsibility pattern in middleware?

How does Laravel handle dependency injection?

How does Laravel handle dependency resolution with the service container?

What are Laravel contracts, and how do they contribute to the architecture?

How does Laravel implement the Observer Pattern?

How does Laravel implement the Strategy Pattern in authentication?

Service Providers & Dependency Injection

What are service providers in Laravel?  

How do service providers fit into the framework’s architecture?  

Service Providers & Facades

What is a service provider in Laravel, and how does it work?  

How do you create and register a custom service provider?  

How does Laravel’s facade pattern work internally?  

What is the difference between facades and dependency injection?  

How do you use the `app()` helper function in Laravel?

Architecture & Patterns

What is the Laravel pipeline and how does it work?  

How does Laravel handle dependency injection?  

What are singleton bindings in Laravel?  

How does Laravel handle request lifecycle?  

Explain Laravel’s event-driven architecture.  

How does Laravel implement the Pipeline Pattern?  

What are some common architectural pitfalls in Laravel applications?  

What is Domain-Driven Design (DDD) and how can you implement it in a Laravel project?  

What are the benefits and drawbacks of using Laravel for monolithic vs. microservices-based applications?  

How do you structure a large-scale Laravel application for maintainability?  

How does Laravel Horizon differ from Laravel queues in terms of architecture?  

Performance & Optimization

How do you optimize Laravel performance?

How do you cache data in Laravel?

Search & Indexing

What is Laravel Scout?

Queues & Background Jobs

How do you use queues in Laravel?

What are jobs and workers in Laravel?

What is the purpose of jobs and queues in Laravel’s architecture?

Events & Broadcasting

Explain Laravel broadcasting.

How do events and listeners fit into Laravel’s architecture?

How does Laravel’s event system work?

File Handling & Storage

How do you handle file uploads in Laravel?

Logging & Monitoring

How do you implement Laravel logging?

Testing & Debugging

How do you test a Laravel application?

Laravel Lifecycle & Internal Mechanisms

How does Laravel’s request lifecycle work?

What is the role of the Kernel in Laravel’s architecture?

What is the difference between service providers and facades in Laravel’s architecture?

What is the role of Facades in Laravel, and how do they work internally?

What is the purpose of the boot() method in service providers?

Extending Laravel

What are Laravel macros?

Core Concepts & Lifecycle  

Explain Laravel’s request lifecycle from the moment a request enters to the response.  

What is the role of `public/index.php` in Laravel?  

How does Laravel handle exceptions and errors?  

How does Laravel implement dependency injection?  

What is the purpose of the Kernel in Laravel?  

How do Laravel’s `bind()` and `singleton()` methods work in the service container?  

How does Laravel’s autoloading mechanism work?  

Caching & Performance Optimization

What are the different types of caching available in Laravel?  

How does Laravel’s cache tagging work?  

How do you cache database queries in Laravel?  

How do you optimize Laravel applications for performance?  

What are some strategies to handle a large number of database queries efficiently?  

How do you configure and use Redis caching in Laravel?  

How does Laravel handle caching in its architecture?  

Testing in Laravel

What is PHPUnit, and how does Laravel use it for testing?  

How do you write a feature test in Laravel?  

How do you mock dependencies in Laravel tests?  

What is Laravel Dusk, and how does it work?  

How does Laravel handle database testing with in-memory SQLite?  

Queues & Jobs

What are Laravel queues, and how do they work?  

How do you implement job retries in Laravel?  

What is Laravel Horizon, and how does it improve queue management?  

How do you manage failed jobs in Laravel?  

How do you prioritize queues in Laravel?  

API Development in Laravel

What is the difference between `resource()` and `apiResource()` in Laravel routing?  

How does Laravel handle API versioning?  

How do you format API responses in Laravel?  

What is Laravel’s `Resource` class, and how do you use it?  

How do you implement rate limiting in Laravel APIs?  

Security

How do you secure a Laravel application against common vulnerabilities?

How does Laravel prevent SQL injection?  

What is CSRF protection in Laravel, and how does it work?  

How do you prevent XSS attacks in Laravel applications?  

How does Laravel encrypt and decrypt sensitive data?  

How do you secure API endpoints in Laravel?

CSRF Protection (@csrf in Blade forms)

SQL Injection Prevention (Eloquent ORM & Query Builder)

Hashing Passwords (bcrypt or Hash::make())

Ecosystem & Deployment

What is Laravel Forge, and how does it help in deployment?  

What is Laravel Vapor, and how does it enable serverless Laravel?  

What are the different ways to deploy a Laravel application?  

How do you configure environment variables for different deployment environments?  

How do you set up Laravel with Docker for local development?  

Performance & Scaling

What is Laravel Octane and how does it improve performance?  

How do you scale a Laravel application?  

How does Laravel handle database connection pooling?  

How do you optimize database queries in Laravel for large-scale applications?  

What are the best practices for writing Laravel applications in a large-scale production environment?  

How does Laravel handle database caching?  

What is the impact of using database queues on performance in Laravel?  

How does Laravel handle database connection pooling and scalability?  

How does Laravel support microservices architecture?  

Multi-Tenancy & Multi-Database Support

How do you implement multi-tenancy in Laravel?  

How does Laravel handle multi-database connections?  

How does Laravel handle multi-tenancy in its architecture?  

How does Laravel support multi-tenancy in database handling?  

How do you implement database sharding in Laravel?  

Queue & Job Management

How do you implement a custom queue driver in Laravel?  

How do you use API resources in Laravel?  

How do you implement database sharding in Laravel?  

What is the purpose of jobs and queues in Laravel’s architecture?  

Elasticsearch & Third-Party Integrations

How do you integrate Laravel with Elasticsearch?  

Miscellaneous Advanced Topics

What are Laravel macros, and how do you use them?  

How do you implement a multi-tenant architecture in Laravel?  

What is Laravel Octane, and how does it impact performance?  

How do you implement a custom Artisan command?  

What is Laravel Scout, and how does it handle full-text search?  

What is Laravel Livewire, and when should you use it?  

How does Laravel handle WebSockets and real-time updates?  

How does Laravel’s task scheduling feature work in its architecture?

How does Laravel integrate with third-party services while maintaining architectural best practices?

How does Laravel handle internationalization and localization in its architecture?

How do you integrate Laravel with NoSQL databases like MongoDB?

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.