Home > Software design >  Is there a difference between redirect()->route() and route()?
Is there a difference between redirect()->route() and route()?

Time:08-21

These two:

return redirect()->route('...');

return route('...');

seem to do the same thing. Is there a reason to not use the shorter form?

CodePudding user response:

return redirect()->route('...');

it will redirect user to specific route

return route('...');

will return a specific route ( link )

CodePudding user response:

route()

its helper function and it generates the URL to a named route.if you see the source code

if (! function_exists('route')) {
    /**
     * Generate the URL to a named route.
     *
     * @param  array|string  $name
     * @param  mixed  $parameters
     * @param  bool  $absolute
     * @return string
     */
    function route($name, $parameters = [], $absolute = true)
    {
        return app('url')->route($name, $parameters, $absolute);
    }
}

redirect()->route()

Here redirect() is helper function to Redirector class.

if (! function_exists('redirect')) {
    /**
     * Get an instance of the redirector.
     *
     * @param  string|null  $to
     * @param  int  $status
     * @param  array  $headers
     * @param  bool|null  $secure
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
     */
    function redirect($to = null, $status = 302, $headers = [], $secure = null)
    {
        if (is_null($to)) {
            return app('redirect');
        }

        return app('redirect')->to($to, $status, $headers, $secure);
    }
}

redirect()->route() Create a new redirect response to a named route.

/**
 * Create a new redirect response to a named route.
 *
 * @param  string  $route
 * @param  mixed  $parameters
 * @param  int  $status
 * @param  array  $headers
 * @return \Illuminate\Http\RedirectResponse
 */
public function route($route, $parameters = [], $status = 302, $headers = [])
{
    return $this->to($this->generator->route($route, $parameters), $status, $headers);
}

Here if you see the source code then you have an option to set the status code and headers but in the case of route() can only generate the URL to a named route.

For better understanding,if you dd(redirect()->route('home'));

enter image description here

if you dd(\route('home')); then its plain url.

enter image description here

  • Related