Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request->except give me an array instead of a Request object in laravel 5

$request->except(['param1']) gives me an array, I would like to receive a Request object..

I'm not sure how to do it...

$employee = EmployeeSnap::firstOrNew(['nss' => $request->nss, 'rfc' => $request->rfc]);

        if ($employee->name != null && $employee->name != "") {
            $employee->setData(Input::except(['bankid', 'bankaccount'])); //Input::except(['bankid', 'bankaccount']) gives me array instead of Request
        } else {
            $employee->setData($request);
        }

        $employee->save();
        $id = $employee->employeeid;
        $code = 200;
        $data = 'Success';
        $message = 'Operation successful';

Any idea?

like image 980
Juliatzin Avatar asked Feb 08 '23 11:02

Juliatzin


1 Answers

Option 1

You can attempt to clone the Request object and unset the unneeded variables, as mentioned by @AlexeyMezenin. However, this is only a shallow copy, so any objects related to the original request will be the exact same objects related to the new request. This may or may not cause you issues.

Option 2

You can also attempt to generate a new request and replace the input. Something along the lines of:

$newRequest = \Illuminate\Http\Request::capture();
$newRequest->replace($request->except(['param1']));

However, depending on how you use this new request, it may cause different issues.

Option 3 (best)

I think the real solution to your problem is to change the setData() method on your EmployeeSnap model. Request objects really should only be used inside Controllers. The controller should be responsible for interacting with the Request to get the data needed, and then it should pass that data to your models as needed.

So, your setData method should look like:

public function setData(array $request) {
    // use your $request array
}

And your controller should look like:

$employee = EmployeeSnap::firstOrNew(['nss' => $request->nss, 'rfc' => $request->rfc]);

if ($employee->name != null && $employee->name != "") {
    $employee->setData($request->except(['bankid', 'bankaccount']));
} else {
    $employee->setData($request->all());
}

// rest of code ...

This helps separate your concerns, keeps your code a little cleaner, and resolves your issue.

like image 159
patricus Avatar answered Feb 10 '23 01:02

patricus