0

Beginner in API

I have table post_tag which is posts table has relation ( many to many ) with tags table.

my controller code ( every thing is good ):

  $post = Post::create($data);

  $post->tag()->attach($request->tags);

  return $this->apiRespone($post , 'Added Post Successfuly', null ,200);

My question is here: now I send array of tags like that! Is that the best way or the correct way to send array ( means when I give this api url to mobile developer, he will know what to do with this api url ?

My way is correct or not ?

enter image description here

Ahmed
  • 163
  • 9
  • "*My way is correct or not?*" - Does it work? If so, then it should be fine. Stackoverflow isn't a code-review site; there's a site for that: https://codereview.stackexchange.com/ – Tim Lewis Jan 08 '20 at 19:41
  • @TimLewis Yeah it works, but I feel sad when the mobile developer said your way is incorrect! he confused me :( so I just ask. bear with man! – Ahmed Jan 08 '20 at 19:55
  • That's just their opinion... If it works, and doesn't cause issues, doesn't affect performance, etc etc, then it's not "wrong". There may be better ways to do it, as suggested below (JSON is pretty widely used for this case), but saying it is wrong is pretty ignorant. The way I see it; you're developing the API. You should be telling *them* the correct (or preferred) way of doing it. – Tim Lewis Jan 08 '20 at 19:57
  • @TimLewis hi Tim, could you pls help with this ? https://stackoverflow.com/questions/59664331/foreach-pivot-table-in-resource-api – Ahmed Jan 09 '20 at 16:29
  • I will if I have time/see the question for myself/can actually help you. Generally, don't ping people for this; it'll happen naturally if it happens at all. – Tim Lewis Jan 09 '20 at 16:43

1 Answers1

1

Although your solution works, a better approach since you are building an endpoint, it would be better to switch your input to accept JSON format rather than using form-data. Make your API endpoint to accept the following payload:

{
  "title": "First Post",
  "desc": "Desc of Post",
  "image": "image3.jpg",
  "category_id": 1,
  "tags": [
    "one",
    "two",
    "three"
  ]
}

In Laravel, you get just grab the tags (or any other properties) with the following:

$tags = $request->input('tags');

For the image, you can allow it to be received in base64 encoded image. The image will look like a bunch of string which should be converted by the client (ios or android) e.g:

{
 image:"/9j/4AAQSkZJRgABAQAAAQABAAD/7QB8UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAF8cAigAWkZCTUQyMzAwMDk2OTAxMDAwMDgxNTIwMDAwNWY2MDAwMDA3NDZmMDAwMDE2YmEwMDAwNDAxYjAxMDBmMTM0MDEwMGY4YzIwMTAwZDkxNDAyMDA1ZDRhMDIwMAD/2wBDAAcHBwcHBwwHBwwRDAwMERcRERERFx4XFxcXFx4kHh4eHh4eJCQkJCQkJCQrKysrKysyMjIyMjg4O"
}

Then in PHP, if you want to save the image on disk, just use base64_decode. See example here.

Hyder B.
  • 7,882
  • 4
  • 38
  • 52