How to modify/set URL in the address bar of the browser with Laravel/PHP?

450 Views Asked by At

Goal
Set/modify the url in the address bar of the browser depending on the DB search result.

Description
I try to develop a small multilang CMS (repository) with Laravel. Therefore i need the possibility to modify the url in the addressbar depending on the user input. For example the user enters www.example.com/page1 and this page/url isn't found in the DB of the cms, i want to redirect to www.example.com/404.
Other use case: The user enters www.example.com/contact, the url is found and i then want to show the url in the browser address bar like this: www.example.com/en/contact.

The code: At the moment i have a PageDataGetter class (repo link), which searchs for the data and returns a DTO with the needed data (or the 404 page data). Then i assemble the data.

PageAssembler

public function assemble(
        PageDataGetterResponseTransfer $pageDataGetterResponseTransfer
    ): PageAssemblerResponseTransfer {

        $pageAssemblerResponseTransfer = new PageAssemblerResponseTransfer();
        
        $pageAssemblerResponseTransfer->setPage(
            response()
                ->view(
                    TemplateInterface::VIEW_PREFIX . $pageDataGetterResponseTransfer->getViewString(),
                    $pageDataGetterResponseTransfer->getPageDataTransfer()->getPageData(),
                    $pageDataGetterResponseTransfer->getStatusCode()
                )
                ->header('Location',  $pageDataGetterResponseTransfer->getUrl())
        );

        return $pageAssemblerResponseTransfer;
    }

In the controller i simply try to return the response like this, but it doesn't change the url in the address bar of the browser.

FrontendController

$pageAssemblerResponseTransfer = $pageAssembler->assemble($pageDataGetterResponseTransfer);

return $pageAssemblerResponseTransfer->getPage();

At least i'm not sure, if it is the right direction, i'm trying to achieve my goal.
I also tried to solve it with a redirect, but there i didn't know how to pass the the string to the view/blade and i also need the possibility to set the status code dynamically.

Maybe someone has a hint for me?

0

There are 0 best solutions below