📜  laravel session flash 2020 - PHP (1)

📅  最后修改于: 2023-12-03 15:32:33.799000             🧑  作者: Mango

Laravel Session Flash 2020 - PHP

In Laravel, the Session Flash is used to store temporary data that can be accessed across multiple requests. It is commonly used to store success or error messages after a user performs an action, such as filling out a form or making a payment.

How to Use Laravel Session Flash

Using Laravel Session Flash is quite simple. To store data in the session, you can use the flash() method on the Session facade. For example, to store a success message, you can do the following:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class MyController extends Controller
{
    public function myMethod(Request $request)
    {
        // Your code here...
        
        Session::flash('success', 'Your action was successful!');
        
        // Your code here...
    }
}

To display the stored data in a Blade template, you can use the session() helper function. For example, to display a success message, you can do the following:

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
Flashing Input Data to Old Input

Another common use case for Laravel Session Flash is to flash input data to the old input, so that the user can correct any errors that occurred during input validation.

To do this, you can use the withErrors() method on the RedirectResponse object. For example, if you have a form that requires the user to input a name, you can validate the input and flash the input data to the old input like this:

use Illuminate\Http\Request;

class MyController extends Controller
{
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required',
        ]);
        
        // Your code here...
        
        return redirect('/')->with('success', 'Form submitted successfully.')->withErrors($validatedData);
    }
}

To display the old input data in a Blade template, you can use the old() helper function. For example, to display the value of the name input field, you can do the following:

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

In conclusion, Laravel Session Flash is a powerful tool that makes it easy to store and display temporary data across multiple requests. It is especially useful when it comes to displaying success or error messages, or when you need to flash input data to the old input.