How to insert data in a Json array into a database via a ajax request in Laravel 5.2
<p>I'm new to Laravel and using version 5.2. I have two models Tour and City which are having a many to many relationship in between. I have already created 3 tables, tours, cities and city_tour in by database and defined the relationships in the models.
Models are as follows.    </p>

<p><strong>Tour Model</strong></p>

<pre><code>class Tour extends Model{

public function cities()
{
    return $this-&gt;belongsToMany('App\City');
}  }
</code></pre>

<p><strong>City Model</strong></p>

<pre><code>class City extends Model{

public function tours()
{
    return $this-&gt;belongsToMany('App\Tour');
}  }
</code></pre>

<p>I'm using the a ajax post request to pass data store method in my TourController. My <em>ajax request</em> is as follows.</p>

<pre><code>$("#btnSave").click(function(){ 

    var path = JSON.stringify(route);
    var token = $('input[name="_token"]').val();

    $.post("/tour",
    {
        tourname: $("#name").val(),
        startpoint: $("#select_startpoint").val(),
        endpoint : $("#select_endpoint").val(),
        waypoints : path,
        '_token': token       
    },function(){
        alert("Path has been saved");
        window.location.href = "/tour";
    });
});
</code></pre>

<p>Here the variable <em>path</em> is a javascript array and i have converted it json string in order to pass in to server. And It contains names of cities as strings.</p>

<p>My <em>Store</em> method is as follows.</p>

<pre><code>public function store(Request $request)
{   

    $tour = new Tour;
    $tour-&gt;tourname = $request-&gt;tourname;
    $tour-&gt;startpoint = $request-&gt;startpoint;
    $tour-&gt;endpoint = $request-&gt;endpoint;        
    $tour-&gt;save();

    $json = $request-&gt;waypoints;
    $waypoints= json_decode($json);

    foreach($waypoints as $point){

        $city = City::where('name', '=', $point-&gt;name)-&gt;firstOrFail();
        $cityid = $city-&gt;city_id;

        $tour-&gt;cities()-&gt;attach($cityid);  
    }  

    redirect()-&gt;action('TourController@index');
}
</code></pre>

<p>As there is a m:n relationship between City and Tour I want to add my cities in to a intermediate table. Here as my cities are in a array, I retrieved their city_id and try to attach that id in to the table one by one using an for each loop. My code is as above. Can any one help.</p>