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);
}
kapitan
  • 2,008
  • 3
  • 20
  • 26

2 Answers2

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);
}
Jeffrey
  • 476
  • 4
  • 13
  • 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 Nov 05 '17 at 14:14
  • @kapitan No, you should put your logic in the Controller. – Jeffrey Nov 05 '17 at 14:17
  • 1
    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. – kapitan Nov 05 '17 at 14:19
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.

kapitan
  • 2,008
  • 3
  • 20
  • 26