How to pass a string or variable with http redirect in laravel?

by lindsey.homenick , in category: PHP Frameworks , a month ago

How to pass a string or variable with http redirect in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , a month ago

@lindsey.homenick 

To pass a string or variable with an HTTP redirect in Laravel, you can use the with() method provided by Laravel's Redirect class.


Here's an example of how to pass a string using an HTTP redirect in a Laravel controller:

1
2
3
4
5
6
public function redirectToPage()
{
    $message = 'Hello, world!';
    
    return redirect('/new-page')->with('message', $message);
}


In this example, the with() method is used to pass the variable $message with the key message to the next page /new-page.


Then, on the /new-page, you can retrieve the passed variable like this:

1
2
3
4
5
6
public function newPage()
{
    $message = session('message');
    
    return view('new-page', compact('message'));
}


In the Blade view file new-page.blade.php, you can then display the message like this:

1
2
3
<div>
    {{ $message }}
</div>


This way, you can pass a string or variable with an HTTP redirect in Laravel.