Reputation:
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 ?
Upvotes: 0
Views: 1579
Reputation: 12226
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.
Upvotes: 1