Laravel redirect() helper doesn't work after overrided

Viewed 104

I have some projects that need to deploy in same subdomain e.g :

  • mainproject.domain.com
  • mainproject.domain.com/secondproject

I've googling and found this discussion https://stackoverflow.com/a/63882428/12392547, his solution using forceRootUrl to change base url didn't works properly on my project.

So my approach to solve this issue is try to override the route method because my project using named routing route('xx.yy.zz') and I was tried to implement this way https://laracasts.com/discuss/channels/general-discussion/override-functions-in-supporthelpersphp?page=1&replyId=188043 and override route method on my own helper and IT WORKS !

below is my code to override route method :

function route($name, $parameters = [], $absolute = true)
{
    $appUrl = "https://".getHostFull()->domain; // in my case: http://mainproject.com
    $appUrlSuffix = env('APP_URL_SUFFIX', '/2021'); // in my case: subdirectory

    if ((bool)env('IS_MAIN')) {
        return app('url')->route($name, $parameters, $absolute);
    }
    // Additional check, do the workaround only when a suffix is present and only when urls are absolute
    if ($appUrlSuffix && $absolute) {
        // Add the relative path to the app root url
        $relativePath = app('url')->route($name, $parameters, false);
        $url = "$appUrl$appUrlSuffix$relativePath";
    } else {
        // This is the default behavior of route() you can find in laravel\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php
        $url = app('url')->route($name, $parameters, $absolute);
    }

    return $url;
}

but sadly, there still an issue with syntax redirect()->route() and redirect()->back() so Iam using same approach like before but there is an error

Call to undefined method Illuminate\Http\RedirectResponse::route

I believe there is something wrong with my code because I just copied it from vendor\laravel\framework\src\Illuminate\Foundation\helpers.php

function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
    $appUrlSuffix = env('APP_URL_SUFFIX', '/2021'); // in my case: subdirectory

    if ((bool)env('IS_MAIN')) {
        return redirect()->to($to, $status, $headers, $secure);
    }

    if (is_null($to)) {
        return app('redirect');
    }

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

Anyone can fix my code or you guys might have others approach to solve my case ?

0 Answers
Related