Showing posts with label Laravel Interview Question. Show all posts
Showing posts with label Laravel Interview Question. Show all posts

Laravel HTTP Request, Methods and Input


Laravel HTTP Request

Laravel HTTP(HyperText Transfer Protocol) request method is the way to structure the request and response to set the communication of Client and server or its a protocol to transfer the data over the web. Http follow the server-client Model. In Laravel HTTP request get processed through routes/web.php by default.

We can access the Http Request by declearing the Illuminate\Http\Request in Controller.

public function personalData(Request $request)
    {
        $name = $request->input('name'); 
    }

HTTP Request Path and Methods

Illuminate\Http\Request instance provides various method to access the Http request and its parameter which is trying to access the application.

path() method will return the information about the url path. For example: Our URL is https://www.abcd.com/my-profile/umesh, if we use path() method to get the request it will return /my-profile/umesh. 

For Example : 
$uriPath = $request->path();

We can fetch the entire url itself using url() method  and fullurl() method. ce url method will return the url without string whereas fullurl method will return with string. Below is the code for your reference.
$urlWthtString = $request->url();  // return url without String
$urlWthString = $request->fullUrl(); // return url with String

Fetching the Request Method

We can fetch the HTTP request type using method() function as well as we can check whether the requested method is satisfying the type using ismethod() function . 

$methodType = $request->method();
// This Will give you the request method type whether it is post, get etc..

if ($request->isMethod('post')) {
    //
}

Laravel Retrieving Input From HTTP Request 


We can retrieve all the input data as a array which is coming through the HTTP Request using all() method.

$inputData = $request->all();

Illuminate\Http\Request instance We can get the request data using input method. we can pass the second argument in input method. If input method don't have the value it will take second argument as default value. See the code below for reference.

$firstName = $request->input('firstName');
$firstName = $request->input('firstName', 'Umesh');
   
We can use input() method without having any argument to get the input value as a associative array.

$input = $request->input();  // this return the input as a associative array.

Checking Input Value is Present or not


We can check whether the input value is there or not, we use has() method. has() method will return the value as true or false.
if ($request->has('firstName')){
   // $request->has('firstName') will return the value as true or false.   
}
⇛ has() method will check the array input also. check the code below for reference.
if ($request->has(['firstName', 'emailId'])){
    // If both array input will be there, It will return true or false.
}

⇛ hasAny() method will check if any input will be there it will return true. Below is the code for your reference.
if ($request->hasAny(['firstName', 'emailId'])){
    // if any Input will be there it will return true
}

Redirecting and Flashing the input


If the validation fails we need to redirect to the same page with the input. Flashing the input with redirect on the page we use withInput() method. Below is the code for your reference.
return redirect('personal-form/save')->withInput();

return redirect('personal-form/save')->withInput($request->except('userpass'));

Handling File Upload using HTTP Request


Sometime we need to access the uploaded file using HTTP request using file() method. The Illuminate\Http\UploadedFile class have file() method which returns an instance. We can check using hasFile() method that HTTP request have the file or not. Below is the code for your reference.

$fileImage = $request->file('candidate_photo');
$fileImage = $request->candidate_photo;
if ($request->hasFile('candidate_photo')){ // }

Uploaded File Path and Extension 


UploadFile class provide some predefined method through which we can access the file path and its Extension.

$Photopath = $request->candidate_photo->path();

$photoextension = $request->candidate_photo->extension();

Laravel Routing and Named Route with Example

laravel Route List and Resource

Concept of Laravel Routing, Resource and list


Laravel Routes are defined in web.php file which is called by default and resides in routes directory. URL prefix is applied directly and automatically in laravel, you don't have to apply the prefix to each route individually. Router methods list are available like get, post, put, patch, delete, any. 

Any form request which point to Route method like post, put, patch, delete you must have to include the csrf token field.

Basic Route Example :

Route::get('/', function () {
    return 'Welcome to Laravel Basic Routing.';
});

Route::get('/user-profile', 'ProfileController@showProfile');

Redirecting Route to another Route in Laravel

Laravel provide redirect route to another route facility. if you want to redirect the one route to another route. Route redirect return 302 status by default, we can customize the status code using third parameter. See the below code for above two statement.

Route::redirect(' /one-route ', '/other-route');
Route::redirect(' /one-route ', '/other-route', 301);

View Route in Laravel

Route::View method is one useful method in laravel which we can use if we want to show the view only. This provide the shortcut way to redirect the route to view without defining all the route and controller. 

Route::view method accepts three parameter, one is URL string, second argument is view name and third argument is some additional parameter as a array. Below is the code for reference.

Route::view('/my-profile', 'user-profile');
Route::view('/my-profile', 'user-profile', ['name' => 'Umesh']);


Laravel Named Route


Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')
->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')
->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004

Laravel Route Prefix Defination

Laravel prefix method can add the prefix to the group of route with given URL. Simple example is most of the web application have the admin section. Now as a developer I want to add admin as a prefix to all the route which point to admin pages. Below is the code for your reference.

Route::prefix('admin')->group(function () {
   
        // You have to define all your route here.
    
});

Apply Middleware on Route

We can assign the middleware to the group of route in the routes Directory. As we know that Middleware act as the middle man between the HTTP request and Application,  it filter and restrict the unwanted HTTP request to access the application. Below is the code for reference.

Route::middleware(['AdminMiddleware', 'AuthMiddleware'])->group(function () {
    
 // Specify All the route in this group.
 
});

Laravel Fallback Route

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});

Current Route Access  

We can Access the current route which is handling the HTTP request  using current,  currentRouteName and currentRouteAction methods. Below is the code example for your reference.

$currentRoute = Route::current();
$routeName = Route::currentRouteName();
$routeAction = Route::currentRouteAction();

100 Top Interview Laravel Question for Fresher and Experience

 

100 Laravel Framework Interview Question


1) Describe Laravel?

 Laravel is MVC(Model View Controller) architecture based open Source php Framework developed by Taylor Otwell. Latest version of Laravel Framework is 7.0 which got released on March 3rd.

Laravel 1st version got released on 9th June 2011.



2) What are the Laravel Framework Feature ?

 Top Feature of laravel Framework is below.

  • CRSF (cross-site request forgery )
  • Eloquent ORM
  • Laravel paginations
  • Database Seeding
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • Unit Testing
  • IOC (Inverse of Control) Container.
  • Job middleware
  • Lazy collections



3) Define Laravel Eloquent ORM ?

Laravel Eloquent feature is object Oriented paradigm approach of database communication. In Eloquent we create Model for each Table in the database, which set the communication (Fetching, Inserting, Deleting, Modifying the Record ) with database. It represent Database Table as a Class.



Laravel Eloquent ORM With Example Read More






4) What is Soft Delete? How to use it in Laravel Model?

Soft Delete is feature of laravel framework which helps when model is soft deleted. In this scenario the data record is not deleted form the database table instead deleted_at timestamp is maintained.




5) Define Laravel Query Builder ?

Query Builder in Larevel is a Package through which we create and run database query Quickly to run the application smoothly. Query Bulider Use PHP Data Object (PDO) where we dont have to worry about the SQL Injection. It can perform all Database Operation such as CRUD, DB Connection, Aggregate Function etc.



Laravel Query Builder With Example Read More






6) Explain Middleware Concept in Laravel?

Laravel Middleware provide a filter as well as it act as interface or Middle-Man between HTTP request and response which access the application. Middleware is a way to filter all the bad or Forgery request which try to access your Application.

Laravel Middleware Type 
  • Global Middleware 
  • Route Middleware


Laravel Middleware With Example Read More






7) Define Aggregate Function ? What are the aggregate function available in Lravel Query Builder?

In Aggregate Function, Database Table Rows are grouped together based on certain Criteria to get specific summary value. Laravel Provide various aggregate function which we can use in our query, list is below for your reference.
  • count() function
  • max() function
  • min() function
  • sum() function
  • avg() function
Note: All Aggregate function defined above ignore NULL Value except Count() function.



8) Explain Laravel Migration? Write the Artisan Command for Laravel Migration ?

Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


Artisan Command for Laravel migration.    php artisan migrate



9) Describe Laravel Reverse Routing ?

Laravel reverse Routing is one of the Awesome Route Feature. Reverse Routing is process of generating the URL based on the Route Deceleration. Reverse Routing sets a relationship between links and web routes.

Consider below route declared as Example (consider your Website as www.abc.com)

Route::get('user-login','UserController@userLogin');

{ { url( '/usre-login' ) } }

$url-link = URL::route('usre-login');

$redirect
-link = Redirect::route('usre-login');

Above three will generate the URL which is below as a example :

URL : www.abc.com/user-login

Now reverse routing is process to generate the url based on Name or other parameter.

  {{ HTML :: link_to_action( ' UserController@userLogin ' ) }}  

This above reverse routing will also generate or point the same URL www.abc.com/user-login .

 
10) What is Artisan ? List some Common Php Artisan command?

 Artisan is command line Interface tool which help in laravel Application Building. To Kmow all this List of Artisan command, Use the below Artisan command.

php artisan list

 List of Common Artisan Command for hassle free Laravel application Development is below:-
  • php artisan list
  • php artisan make:controller controller-name
  • php artisan make:model model-name  
  • php artisan migrate
  • php artisan make:middleware middleware-name  
  • php artisan tinker


11) Define Controller ?

Controller handle all the HTTP Request logically and divert the Web Traffic to View and Model. It Contain all the Http Handling Logic within Single Class. Artisan Command to create the Controller is below for your Reference.

php artisan make:controller controllerName

Controller is C of  MVC(Model View Controller).


12) List out some Laravel Official Packages?

Laravel Packages list is below for your reference.
  • Dusk Package
  • Envoy Package
  • Horizon Package
  • Cashier Package
  • Passport Package
  • Scout Package
  • Socialite Package
  • Telescope Package
 

13) What is the difference between find() and where() method in laravel?

The Major Difference between them is find() method always use Primary Key to filter the table record, whereas where() method uses any table column to filter the table record set.

find() method will return the single table row from the database. where() method return multiple record based on the condition.



14) What is Named Route in Laravel ?

Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004



15) Define Laravel Validation?

Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation purpose is to get the exact data what is required for application.

You can use validate method for data filteration.

$validatedData = $request->validate([
            'FULL_NAME' => 'required|max:25',
            'mobile' => 'required|digits:10|unique:valid_table,mobile',
            'email' => 'required|email|max:255',
        ]);

You can use Validation make() method to create manual validator.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



16) Define Route::fallback method with Example?

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});




Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post