Skip to content

Instantly share code, notes, and snippets.

@haakym
Created February 26, 2017 20:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haakym/8f36a857ddd9bf051079085dd732b517 to your computer and use it in GitHub Desktop.
Save haakym/8f36a857ddd9bf051079085dd732b517 to your computer and use it in GitHub Desktop.
Laravel accessing the request object

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...

  1. 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

  1. Use the request() helper function

class UserController extends Controller
{
    public function register(Request $request)
    {
        $username = $request('username');
    }
}
  1. 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:

  1. $request->get('username')

or

  1. $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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment