To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request
class on your controller method. The incoming request instance will automatically be injected by the service container:
For Example(1)
1.Create route in web.php file to view form using blade file
Route::get('form', 'demoController@form');
2.Create demo controller using below command
php artisan make:controller demoController -mcr
3.Open demoController and Implement code to access request from form
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class demoController extends Controller
{
public function form(){
return view('form');
}
}
4.Create form.blade.php in resource\view folder as below created
<!DOCTYPE html>
<html>
<head>
<title>Accessing Request In Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="form-group col-sm-2"></div>
<div class="form-group col-sm-8">
<div class="well">
<form method="post" action="">
@csrf
<div class="form-group col-sm-12">
<label>Name</label>
<input class="form-control" type="text" name="Name" value="">
</div>
<div class="form-group col-sm-12">
<label>Description</label>
<input class="form-control" type="text" name="Description" value="">
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" >
</div>
</form>
<div class="form-group col-sm-2"></div>
</div>
</div>
<br>
</div>
</body>
</html>
5.To store data create path to controller in form action as below created
<form method="post" action="{{url('formstore')}}">
6.Now Open demo controller and create formstore function to access the request
public function formstore(Request $request){
return $request->all();
}
Dependency Injection & Route Parameters
If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so:
Route::put('demo/{id}', 'demoController@update');
You may still type-hint the Illuminate\Http\Request
and access your route parameter id
by defining your controller method as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class demoController extends Controller
{
public function update(Request $request, $id)
{
//
}
}
Accessing The Request Via Route Closures
You may also type-hint the Illuminate\Http\Request
class on a route Closure. The service container will automatically inject the incoming request into the Closure when it is executed:
use Illuminate\Http\Request;
Route::get('/', function (Request $request) {
//
});