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

Antonella's avatar

translate Show per view to Show per API

public function show(Article $article) { return view('articles.show',['article'=>$article]); }

if this method wanted to translate into API or rather return not the whole set but the single element so it works for me and I pass the data to the view, api does not work.

it makes me empty together.

I used the following function before and it worked:

 public function show($id)
 {
     return response()->json(Article::find($id), 200);
 }

I just wanted to take advantage of the techniques from lesson 26 Leverage Route Model Binding

0 likes
7 replies
ismaile's avatar

In an API, you wouldn't use a view, so you can return the variable directly:

// Instead of
return view('articles.show',['article'=>$article]);
// In API, you would have
return $article;

For route model binding, you would have:

public function show(Article $article)
 {
     return $article;
 }
Antonella's avatar

if I use this approach it gives me empty set

public function show(Article $article)
{
    return response()->json($article, 200);
}

when I go .../show/1

gives me back []

if instead I use the method you suggest

public function show($article)
{
    return $article;
}

when I go .../show/1 gives me back 1 when I go .../show/2 gives me back 2 ....

ismaile's avatar

Actually, you should use:

public function show(Article $article)
{
    return $article;
}
Antonella's avatar

it doesn't work I don't know if you tried to do DD, there is no data

Sinnbeck's avatar

Can you show the row with id 1 in your database (articles table)

Antonella's avatar

id=1, user_id: 1, title: "Consequatur est amet enim illo nihil.", excerpt: "Incidunt esse quod praesentium aut velit veniam vitae aut.", body: "Rem dolorem ut quas qui fugiat explicabo. Rerum temporibus delectus voluptas officiis quia aut. Et molestiae et unde quibusdam hic. Nemo et error nobis ea repellendus adipisci eaque.", updated_at: "2020-09-17 11:05:43", created_at: "2020-09-17 11:05:43", id: 1, }, ], }

ismaile's avatar
ismaile
Best Answer
Level 30

I would take a look at your route definition, after Route::get, you should have something like:

'articles/{article}'

having {article} is important

1 like

Please or to participate in this conversation.