Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

matttonks11's avatar

Session Data

I have some session data that populates a form which I am then trying to validate. However when the validation fails and I'm redirected back to the form, the data is no longer there. How do I keep the form data when the validation fails?

public function getBookDetails(){
        $isbn = Input::get('book_isbn');
        $data = json_decode(file_get_contents("https://www.googleapis.com/books/v1/volumes?q=isbn:". $isbn));

        return redirect('books/create')->with([
            'data' => $data,
            'isbn' => $isbn
        ]);
    }

public function create()
    {
        $data = \Session::get('data');
        $isbn = \Session::get('isbn');

        return view('books.create', compact(['data', 'isbn']));
    }

public function store(Request $request)
    {
        $request->validate([
            'book_number' => 'required'
        ]);

        Book::create([
            'id'            => $request->book_number,
            'isbn'          => $request->book_isbn,
            'title'         => $request->book_title,
            'author'        => $request->book_author,
            'publisher'     => $request->book_publisher,
            'description'   => $request->book_description,
            'image'         => $request->book_image,
            'category'      => $request->book_category
        ]);

        return redirect('/books');
    }

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Old data is automatically flashed into the session on validation failure. You can get it using the old() helper in the Blade template. Maybe if you utilise this feature to flash those inputs inside the getBookDetails method in the first instance, you can lean on the old() helper in both cases:

        return redirect('books/create')->withInput([
            'data' => $data,
            'isbn' => $isbn
        ]);

In the view:

<input type="text" name="isbn" value="{{ old('isbn') }}">

Now, whether you are coming from the getBookDetails redirect, or redirecting back from a validation failure, you will have the values you want/need

Please or to participate in this conversation.