1

How can I return a variable from Form Requests (App\Http\Requests) to Controller (App\Http\Controllers)?

I am saving a record on function persist() on Form Requests.

My goal is to pass the generated id so that I can redirect the page on edit mode for the user. For some reason, the Controller cannot receive the id from Form Requests.

App\Http\Requests\MyFormRequests.php:

function persist()
{
  $business = Business::create([
    'cart_name' => $this['cart_name'],
    'product' => $this['product']
  ]);

  return $myid = $business->id;
}

App\Http\Controllers\MyControllers.php:

public function store(MyFormRequests $request)
{
   $request->persist();

   return redirect()->route('mypage.edit.get', $request->persist()->$myid);
}
5

2 Answers 2

0

Important

I must add that this is not the recommended way. Your FormRequest should only be responsible for validating the request, while your Controller does the storing part. However, this will work:

App\Http\Requests\MyFormRequests.php:

function persist()
{
    return Business::create([
        'business_name' => $this['business_name'],
        'nationality' => $this['nationality']
    ])->id;
}

App\Http\Controllers\MyControllers.php:

public function store(MyFormRequests $request)
{
    $id = $request->persist();

    return redirect()->route('register.edit.get', $id);
}
Sign up to request clarification or add additional context in comments.

3 Comments

i saw this on the laracasts tutorial episode, so i thought that it would make my controller cleaner because the actual code has some 50 textboxes on it. should i really not put it on the FormRequest?
@kapitan No, you should put your logic in the Controller.
thank you, it's actually working when the whole saving code is on the Controller. i think ill trust you and put it back on the Controller. ill just leave the validation on the FormRequest. sigh - just when i made it work (smile). thanks @Jeffery.
0

A guy name Snapey helped me:

public function store(MyFormRequests $request)
{
  $business = $this->persist($request);

  return redirect()->route('register.edit.get', $business->id);
}

private function persist($request)
{
  ....
  return $business;
}

hope this could help someone in the future.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.