Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dave Wize's avatar

return redirect as a new tab?

  return redirect($url);

I want this to open that URL in a new browser tab instead of redirecting. I know I can return a view which will render a script tag like this

<script>
    window.open('{{ $url }}', '_blank');
</script>

But it feels funny to do so, is there a backend way to do that?

0 likes
2 replies
LaryAI's avatar
Level 58

No, there is no backend way to directly open a URL in a new browser tab using the redirect function in Laravel. The redirect function is specifically designed to perform a server-side redirect, which means it will send a response to the client's browser instructing it to navigate to a new URL.

If you want to open a URL in a new tab, you will need to use JavaScript on the client-side. The approach you mentioned in your question, using window.open, is the correct way to achieve this behavior.

Here's an example of how you can modify your code to achieve the desired result:

return view('open_new_tab', ['url' => $url]);

In your open_new_tab.blade.php view file:

<script>
    window.open('{{ $url }}', '_blank');
</script>

This will render the JavaScript code in the browser, which will open the specified URL in a new tab.

hupp's avatar

@dave wize First you can do only with back-end this thing. Its browser behaviour to do that. Here is short and sweet example to do like that, you can modify the code as per your need :

<body>
    <button id="openUrlBtn">Open URL in New Tab</button>
    <script>
        $(document).ready(function() {
            $('#openUrlBtn').click(function() {
                // Send an Ajax request to fetch the URL
                $.ajax({
                    url: '/get-url', // Replace with your Laravel route
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        // Open the URL in a new tab
                        window.open(data.url, '_blank');
                    },
                    error: function() {
                        alert('Failed to fetch the URL.');
                    }
                });
            });
        });
    </script>
</body>

Laravel's Controller :

public function getUrl()
{
    $url = 'https://example.com';
    return response()->json(['url' => $url]);
}

Let me know your feedback.

Please or to participate in this conversation.