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

Troj's avatar
Level 4

Redirect post with external link

I'm trying to mask my external urls, in the first place when a post has an external link in the database and no original content for a single post page itself. But when it has an external link and an original content page itself, the external url should be masked (look like the post url) on that page and should be redirected as well to the external page when clicked.

So the visitor needs to see the post url when they hover it for example, but when they click on it they should be redirected.

This is what i got so far in my PostController, and this works for the index pages where i use the $post->url variable. I can't figure out how to make this external_url on a single post page redirect from the controller, because of the already existing if statement.

I hope you understand what i'm trying to achieve. Can anyone help me in the right direction?

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class PostController
{
    public function __invoke(Post $post)
    {

    	$mediaItems = $post->getMedia('multi_collection');

        if (! empty($post->external_url) && $post->original_content == 0) {
            return redirect()->away($post->external_url);
        }

        return view('posts.show', compact('post', 'mediaItems'));
    }

}
0 likes
3 replies
Olsza's avatar

I would try instead of return redirect()->away($post->external_url); to return redirect($post->external_url);

Troj's avatar
Level 4

@olsza Thanks, you're right, thats a small improvement. But it's not really an answer to my question.

Because i've that if statement in place (this works when i'm on any index page) i cant figure out how to redirect the same url (with a link on that page) when i'm on the actual page. It should show the url of the page i'm on and only when i click on it redirect to the external url.

Olsza's avatar

if you have something like in web.php, for example

Route::get ('post/{id}', function() {.....})->name('nameRoutePost');

that's where you have to display links to the article, after all

{{ route('nameRoutePost', $idPost) }}

the link is displayed to your article, and if the Post has a redirect, the redirect function will work and not display the post.

Please or to participate in this conversation.