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

untymage's avatar

How to redirect to another api resource


public function show(Thread $thread)
{

    if($thread->haveTypeId()) return redirect(route('api.thread.show', $thread->type_id));

    return new ThreadResource($thread);
}

I have a nullable type_idcolumn in my thread table, I want to check if there is a type_id in given thread then redirect to thread url with type_id not id in table, So i redirects user to correct url but because i use return redirect i cannot reach to ThreadResource hence i give only blank page with no json.

How to redirect and show api resource ?

0 likes
4 replies
Martal's avatar

@untymage

Maybe $request->expectsJson() could help you?

Like

use Illuminate\Http\Request;

public function show(Request $request, Thread $thread)
{
    if ($request->expectsJson()) {
        return new ThreadResource($thread);
    }

    if($thread->haveTypeId()) {
        return redirect(route('api.thread.show', $thread->type_id));
    }
}
untymage's avatar

I always expects json from the api url so on that scenario i can not reach the if($thread->haveTypeId())

Martal's avatar

Redirect is a html response, resource is a json response. You could not get two responses on one request.

You should do two requests anyway.

Martal's avatar

Ok. What about this approach?

public function show(Thread $thread)
{

    if(! $thread->haveTypeId()) {
        return new ThreadResource($thread);
    }

    return redirect(route('api.thread.show', $thread->type_id));
}

Please or to participate in this conversation.