Undefined variable in blade after redirect

Viewed 1029

I am using Laravel 7 and PHP 7.4.

I have form in my project. User can submit the form and I can generate report on values the user provided with. Initial issue was that the form was resubmitting on page refresh that was undesirable. I tried to prevent it with redirect-> but the issue is I'm unable to fetch the variable from controller into my view.

This is error on my blade.

Undefined variable: seller

Controller

 $seller = Sellers::take(1)->latest()->get();
 return redirect()->route('private_seller_report')->with(['seller' => $seller]);

Blade

@php
  $seller = Session::get('seller');
@endphp

    @foreach($seller as $row)
      <a href="#">{{$row->seller_name}}</a>
    @endforeach

So my ultimate goal is to prevent the form submission on refresh.

2 Answers

Here is an example of how you can do it. The ->with() method is not intended for this use, but you can just pass data in the route method instead, like so:

Route::get('/first-route', static function() {
    return redirect()->route('second-route', ['data' => [1, 2, 3]]);
});

Route::get('/second-route', static function(\Illuminate\Http\Request $request) {
    return view('test-view', ['data' => $request->input('data')]);
})->name('second-route'); 

Keep in mind that you are redirecting to another route, so you need the route you redirected to, to pass the data into the view. In this example, you can see that I pass [1, 2, 3] into second-route and then get the data via the request object. Then I pass that into the view in the second-route.

If I do a dd($request->input('data'); in second-route, I will get:

array:3 [
  0 => "1"
  1 => "2"
  2 => "3"
]

So my best guess is that you never pass the data into the view, after the first route redirects to the next.

UPDATE: Take a second and read the documentation about the ->with() method https://laravel.com/docs/7.x/redirects#redirecting-with-flashed-session-data and look at the PHPDoc of the code in RedirectResponse.php: Flash a piece of data to the session.

You can see here what the "flash" is used for: https://www.itsolutionstuff.com/post/laravel-5-implement-flash-messages-with-exampleexample.html

first time you need to call sellerPage method using this route.

Route::get('/seller/page','SellerController@sellerPage')->name('private_seller_report');

  public function sellerPage()
  {
    $seller = Sellers::take(1)->latest()->get()->toArray();
    return view('your.blade')->with(['seller' => $seller]);
  }
Related