Difference between Laravel $request->input(), $request->get(), and $request->name direct property
If you’ve been around Laravel for a while, you might have seen there are three ways in controllers to retrieve inputs from the submitted form. For example, if you are trying to retrieve the name of a user from a form. The user controller might have one of the following lines of code:
public function store(Request $request)
{
$name = $request->input(‘name’);
// Or
$name = $request->name;
// Or
$name = $request->get(‘name’);
}
Now the question is what the difference is between these three techniques, and which one is preferred?
$request->input()
From the Laravel 5.3 docs, there are three distinctions that set the $request->input()
method apart.
The
$request->input()
method can be used with any HTTP verb to retrieve data (bothGET
orPOST
request).
$name = $request->input('name');
A default value can be set when using the
$request->input()
method by adding a 2nd (optional) parameter.
$name = $request->input('name', 'Sally');
You can use dot notation to access forms that have names that are arrays. For example, if you were using a form with a name like this:
<input type="text" name="products[0][name]">
then your controller can retrieve that form input using:
$name = $request->input('products.0.name');
Direct property
When using direct properties, Laravel will first look for the parameter’s value in the request payload. If it is not present, Laravel will search for the field in the route parameters. The dynamic property will return the input whether the input is coming from a GET
or POST
request.
$name = $request->name;
$request->get()
The $request->get()
method can be confused with the Eloquent and Query Builder get()
methods that retrieve results from a query. The below code block is a bit blurry in terms of what get()
method is retrieving data from the database and which one is retrieving data from the form:
$qb_users = DB::table('users')->get();
$eloquent_user = App\User::find(1)->get();
$input_user = $request->get(‘user’);
You might think that it’s not so bad having a couple of different get()
methods, even if they are all frequently used. This means the end result could end up looking something like this:
Route::get($uri2,$callback);
Route::get($uri3,$callback);
Route::get('user/{id}', function ($id) {
$qb_users = DB::table('users')->get()
$qb_names = DB::table('names')->get()
$qb_numbers = DB::table('numbers')->get()
$qb_comments = DB::table('comments')->get();
$eloquent_user1 = App\User::find(1)->get();
$eloquent_user2 = App\User::find(2)->get();
$eloquent_user3 = App\User::find(3)->get();
$eloquent_user4 = App\User::find(4)->get();
$input_user1 =$request->get(‘user1’);
$input_user2 =$request->get(‘user2’);
$input_user3 =$request->get(‘user3’);
$input_user4 =$request->get(‘user4’);
Please login or create new account to add your comment.