So say you have a form like this:
<form method="POST" action="users/register">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
Then you want to access the request in your controller, you have a couple of methods...
- Pass
Request
object via dependency injection
use Illuminate\Http\Request;
class UserController extends Controller
{
public function register(Request $request)
{
$username = $request->get('username');
}
}
See: https://laravel.com/docs/5.4/requests#accessing-the-request
- Use the
request()
helper function
class UserController extends Controller
{
public function register(Request $request)
{
$username = $request('username');
}
}
- Plain PHP ($_POST or $_GET globals)
class UserController extends Controller
{
public function register(Request $request)
{
$username = $_POST['username'];
}
}
Further notes on 1 & 2 (the "laravel" way of doing it)...
You can get a specific item from the request using two methods:
$request->get('username')
or
$request->input('username')
AFAIK they are the same
They also accept a second parameter which returns a default value if the request key is empty...
$request->get('username', 'some default string here')
Get all the request data like this:
$request->all()
get only specific parts:
$request->only('first_name', 'surname')
except, opposite to only:
$request->except('middle_name')
You can also check for the existence of a value before doing anything
if ($request->has('middle_name')) {/* do something*/}
Read the docs for more info https://laravel.com/docs/5.4/requests#retrieving-input
and also try checking out the API which lists all the Request object's methods: https://laravel.com/api/5.4/Illuminate/Http/Request.html
Hope this helps!