user3903685 user3903685 - 5 months ago 10
PHP Question

Laravel: Can't set object values

I have a form in Laravel that when it submits, the function

donorUpdate
is going to be called, and it will save the data to the database. Here is the exact code of the function.

My aim is, the form contains the field name
DonorPrefix
that when it's empty, the default value should be
Mx.
. I have tried the code below, and it doesn't work.

public function donorUpdate(Request $request, Donor $donor){
if($request->has('DonorPrefix') == false || $request->DonorPrefix == '' || $request->DonorPrefix == null){
$request->DonorPrefix = 'Mx.';
}
$donor->update($request->all());
return redirect('/donor/'.$donor->DonorID);
}


This is where the weird part start: My debugging attempt is that I commented the
return redirect('/donor/'.$donor->DonorID);
line and replace with
return $request->all()
, the value for
DonorPrefix
is
""
(Empty string).

However when I tried
return $request->DonorPrefix
, the prefix
Mx.
returned.

Why isn't the value of
DonorPrefix
is
Mx.
on
$request->all()
, but is
Mx.
on
return $request->DonorPrefix
?

Edit: I'm certain that other parts of code works like charm. Things are smooth untill I tried adding this 'default value' function.

Answer

You can't set request parameters like $request->DonorPrefix = '...'.

To set a parameter on the request you need to use offsetSet like this:

$request->offsetSet('DonorPrefix', 'Mx.');

Also, the has() method already ensures that it is a non-empty string so you can remove some of your checks, and simplify your code like this:

if(!$request->has('DonorPrefix')){
    $request->offsetSet('DonorPrefix', 'Mx.');
}
Comments