InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What are accessors and mutators? |
|
Answer» Accessors are a way to retrieve data from eloquent after doing some operation on the retrieved fields from the database. For example, if we need to combine the first and last names of users but we have two fields in the database, but we want whenever we fetch data from eloquent queries these names need to be combined. We can do that by creating an accessor like below: public function getFullNameAttribute() { return $this->first_name . " " . $this->last_name; }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: public function setFirstNameAttribute($value){ $this->attributes[‘first_name’] = strtoupper($value);}So, whenever we are setting this field to be anything: $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. ConclusionLARAVEL 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. |
|
| 2. |
What are queues in Laravel? |
|
Answer» While building any application we FACE a SITUATION where some tasks take time to process and our page gets loading until that task is finished. One task is sending an EMAIL when a user REGISTERS, we can send the email to the user as a background task, so our main thread is responsive all the time. Queues are a way to run such tasks in the background. |
|
| 3. |
What are contracts? |
|
Answer» LARAVEL Contracts are a set of interfaces with implementation methods to complete the core tasks of Laravel. Laravel ContractsFew 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. |
|
| 4. |
What are collections? |
|
Answer» Collections in laravel are a WRAPPER over an ARRAY of data in Laravel. All of the responses from Eloquent ORM when we query data from the database are collections (Array of data records). Collections give US handy methods over them to easily WORK with the data like LOOPING over data or doing some operation on it. |
|
| 5. |
What is dependency Injection in Laravel? |
|
Answer» 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. |
|
| 6. |
How to create a route for resources in laravel? |
|
Answer» For creating a resource ROUTE we can use the below COMMAND: Route::resource('blogs', BlogController::CLASS);This will CREATE routes for six ACTIONS index, create, store, show, edit, update and delete. |
|
| 7. |
What is Middleware and how to create one in Laravel? |
|
Answer» Middleware gives developers the ability to inspect and filter incoming HTTP requests of our application. One such middleware that ships with laravel are the authentication middleware which checks if the USER is authenticated and if the user is authenticated it will go further in the application otherwise it will throw the user back to the login screen. We can ALWAYS CREATE a new middleware for our purposes. For CREATING a new middleware we can USE the below artisan command: php artisan make:middleware CheckFileIsNotTooLarge The above command will create a new middleware file in the app/Http/Middleware folder. |
|
| 8. |
What are route groups? |
|
Answer» Route GROUPS in laravel is used when we NEED to group route ATTRIBUTES like middlewares, prefixes, etc. we use route groups. It saves us a headache to PUT each attribute to each route. Syntax: Route::middleware(['throttleMiddleware'])->group(function () { Route::GET('/', function () { // Uses throttleMiddleware }); Route::get('/user/profile', function () { // Uses throttleMiddleware });}); |
|
| 9. |
What are named routes? |
|
Answer» A named route is a route definition with the name assigned to it. We can then use that name to CALL the route anywhere ELSE in the application. Route::get('/hello', 'HomeController@INDEX')->name('index');This can be accessed in a controller using the following: return redirect()->route('index');
|
|
| 10. |
How to define routes in Laravel? |
|
Answer» Laravel ROUTES are defined in the routes file in routes/web.php for web application routes. Routes can be defined using Illuminate\Support\Facades\Route and calling its static methods such as to get, post, put, DELETE, etc. 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. |
|
| 11. |
What is the register and boot method in the Service Provider class? |
|
Answer» The register method in the Service Provider class is used to bind classes or SERVICES to the Service Container. It should not be used to ACCESS any other functionality or classes from the application as the service you are accessing may not have loaded yet into the container. The boot method runs after all the dependencies have been included in the container and now we can access any functionality in the boot method. Like you can create ROUTES, create a view composer, ETC in the boot method. |
|
| 12. |
What is a Service Provider? |
|
Answer» A Service Provider is a way to bootstrap or REGISTER services, events, etc before booting the application. Laravel’s own bootstrapping happens using Service PROVIDERS as well. Additionally, registers service CONTAINER bindings, event listeners, MIDDLEWARES, and even routes using its service providers. If we are creating our application, we can register our FACADES in provider classes. |
|
| 13. |
What is a Service Container in Laravel? |
|
Answer» Service Container or IoC in laravel is responsible for managing class dependencies MEANING not every file needs to be injected in class manually but is done by the Service Container automatically. Service Container is mainly used in injecting class in controllers LIKE Request object is injected. We can also inject a Model based on id in route binding. For example, a route like below: Route::GET('/profile/{id}', 'UserController@profile');With the controller like below. public function profile(Request $request, USER $id){ // }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. |
|
| 14. |
How to do request validation in Laravel? |
|
Answer» Request validation in laravel can be done with the controller method or we can CREATE a request validation class that HOLDS the rules of validation and the error messages associated with it. One example of it can be seen below: /** * 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', ]); // The blog post is valid...} |
|
| 15. |
What are Requests in Laravel? |
|
Answer» Requests in Laravel are a way to interact with incoming HTTP requests along with sessions, cookies, and even files if submitted with the REQUEST. The CLASS responsible for doing this is Illuminate\Http\Request. 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. |
|
| 16. |
What is Localization in Laravel? |
|
Answer» LOCALIZATION is a way to serve content concerning the client's language preference. We can create different localization FILES and use a laravel HELPER method like this: `__(‘auth.error’)` to retrieve translation in the current locale. These localization files are located in the resources/lang/[language] FOLDER. |
|
| 17. |
Explain logging in Laravel? |
|
Answer» Laravel LOGGING is a WAY to log information that is HAPPENING inside an application. Laravel provides different channels for logging like file and slack. Log MESSAGES can be WRITTEN on to multiple channels at once as well. We can configure the channel to be used for logging in to our environment file or in the config file at config/logging.php.
|
|
| 18. |
What are Events in Laravel? |
|
Answer» In Laravel, Events are a way to subscribe to different events that occur in the application. We can make events to represent a particular event like user logged in, user logged out, user-created post, etc. After which we can listen to these events by MAKING Listener CLASSES and do some tasks like, user logged in then make an entry to audit LOGGER of application. For creating a new Event in laravel, we can call below artisan command: php artisan make:event UserLoggedIn This will create a new event class like below: <?phpnamespace 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) { // }} |
|
| 19. |
What are facades? |
|
Answer» Facades are a way to register your class and its methods in LARAVEL Container so they are available in your whole APPLICATION after GETTING resolved by Reflection. The main benefit of using facades is we don’t have to remember long class names and also don’t need to require those classes in any other class for using them. It also gives more TESTABILITY to the application. The below image could HELP you understand why Facades are used for: Facades in Laravel |
|
| 20. |
What is throttling and how to implement it in Laravel? |
|
Answer» Throttling is a process to rate-limit requests from a particular IP. This can be used to PREVENT DDOS attacks as well. For throttling, Laravel provides a middleware that can be applied to routes and it can be added to the global middlewares list as well to execute that middleware for each request. Here’s how you can ADD it to a particular ROUTE: 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. |
|
| 21. |
What is Eloquent in Laravel? |
|
Answer» 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:
|
|
| 22. |
What are Relationships in Laravel? |
|
Answer» Relationships in Laravel are a way to define RELATIONS between different models in the applications. It is the same as relations in RELATIONAL databases. Different relationships available in Laravel are:
Relationships are defined as a method on the model class. An example of One to One relation is shown below. <?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class User extends Model{ /** * Get the phone associated with the user. */ public function phone() { return $this->hasOne(Phone::class); }}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: <?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class User extends Model{ /** * Get the addresses for the User. */ public function addresses() { return $this->hasMany(Address::class); }}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. |
|