fightstarr20
fightstarr20

Reputation: 12598

Laravel 5 API - Handle arrays

I am work with Laravel 5 and have implemented a working Restful API. I am trying to allow posts to be created by passing in an array like this...

post
  title
  excerpt
  content
  image
post
  title
  excerpt
  content
  image

The API currently works great for posting one individual post but how can I handle the array of posts instead?

Does anyone have an example I can see?

Upvotes: 1

Views: 4452

Answers (2)

MartinLeitgeb
MartinLeitgeb

Reputation: 63

did you try to send JSON in the body? Here is a link with an example

Request body could look like the following:

{  
   "parameters":[    
      {    
         "value":{    
            "array":{    
               "elements":[    
                  {    
                     "string":{    
                        "value":"value1"  
                     }  
                  },  
                  {    
                     "string":{    
                        "value":"value2"  
                     }  
                  },  
                  {    
                     "string":{    
                        "value":"value3"  
                     }  
                  }  
               ]  
            }  
         },  
         "type":"Array/string",  
         "name":"arrayvariable"  
      }  
   ]  
}

This will convert the array every time you get it from the DB and every time you save it to the DB.

And here is an example using laravel casting link

Use attribute casting. Open your IdModel model and add this:

 protected $casts = [
     'id' => 'array' ];

Upvotes: 1

Gordon
Gordon

Reputation: 316979

If you are using the Resource Controller, you should have a PostsController with a method store(). I am assuming your request payload is some JSON like this:

{"posts": [{"title":"foo"},{"title":"bar"}, …]}

So you need to json_decode the input. Then pass it to your database:

public function store() 
{   
    $posts = json_decode($request->input('posts', '')); 
    if (is_array($posts)) {
        DB::table('posts')->insert($posts);
    }
}

There is probably some plugin or middleware or whatever to automatically decode the JSON payload. But apart from that, there is nothing special about doing what you ask for.

If you don't want to use the store() method (because it already stores a single Post or something) you can just add another route for your multiple Posts.

Upvotes: 3

Related Questions