RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

ternary condition in laravel

I have to implement the remember me functionality, so I have to pass the value for $remember as a second argument in the Auth:attempt(); function. But the problem is when I am using this syntax for setting value in $remember, it displays syntax error

$remember = isset($request->input('remember')) ? true : false;
----------------------------------------------^//Expected: variable

But when I am using this syntax, it will not give any error

$remember = isset($request->remember) ? true : false;

Upvotes: 2

Views: 10911

Answers (4)

Shams Reza
Shams Reza

Reputation: 1097

Try this

$r = $request->input('remember');
$remember = isset($r)?true:false;

Upvotes: 0

nch7
nch7

Reputation: 110

Request class already has a built-in method to check if a parameter is set:

if ($request->has('remember')) {
    // remember is set
} else {
    // remember is not set
}

But there is a better way to do what you are trying to achieve. request class also has a method get, it accepts the key as a first argument and the default value as the second (which is returned in case the key is not set)

So you can just write it like this:

Auth::attempt([...], $request->get('remember', false));

Upvotes: 2

Maraboc
Maraboc

Reputation: 11083

has is used like this :

$remember = $request->has('remember'); //return true if the remember is selected :)

For your question what is the difference between above two syntaxes :

It's because isset is a language construct and not a real function. It is mentioned in the docs:

Warning

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Use has():

$request->has('remember')

You should use the has method to determine if a value is present on the request. The has method returns true if the value is present and is not an empty string.

Upvotes: 2

Related Questions