Tiến Marion
Tiến Marion

Reputation: 109

Laravel: use redirect outside Controller?

I have a route

Route::get('/abc', function () {
    return view('common.abc');
});

When I access http://domain.com/abc it's work well.

And in Controller, I use

Redirect::to('/abc')

it's work well.

==> BUT, I need to call redirect outside Controller (Model, Lib etc....) How can I do that? I always get an error when call redirect outside the Controller.

Upvotes: 4

Views: 2887

Answers (3)

Anurak Kingkaew
Anurak Kingkaew

Reputation: 101

use Illuminate\Support\Facades\Redirect;

Redirect::to(url('blah-blah'))->send();

You can also use named routes with parameters like so:

Redirect::route('route.name.here', ['foo' => 'bar'])->send();

If you are in a controller, you normally return the redirect. However, outside of a controller, you need to use ->send() to tell it to "go now".

Upvotes: 9

Sergey Lepesh
Sergey Lepesh

Reputation: 93

I think this should help.

abort(200, '', ['Location' => '/abc']);

Upvotes: 5

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

I did small research and it seems it's impossible to use Laravel redirect in a model(), for example.

But you could redirect manually to URL:

$url = route('/abc');
header('Location: '.$url);

http://php.net/manual/en/function.header.php

Upvotes: 1

Related Questions