Reputation: 522
I’m new to Laravel. I’m using Laravel 5.2 and I’ve faced a problem in inserting data in to pivot table which I used to handle a many to many relationship. For passing data into the sever I’m using a jquery ajax post request. It’s code is as follows.
$("#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";
}); });
Here route is a JavaScript array with set of strings and I’m using Json to pass the values in server. Here I’m using an RESTful resource controller to handle the request and its store method is as follows.
public function store(Request $request){
$user = Auth::user();
$tour = new Tour;
$tour->name = $request->tourname;
$tour->user_id = $user->id;
$tour->startpoint = $request->startpoint;
$tour->endpoint = $request->endpoint;
$tour->save();
$json = $request->waypoints;
$waypoints = json_decode($json);
foreach($waypoints as $waypoint){
$city = City::where('name', '=', $waypoint)->firstOrFail();
$tour->cities()->attach($city->id);
} }
Here in inserting data into pivot table I want obtain the city_id
of a particular city from the database first, as I only have it’s name in the array.
As I execute the code the tour table get updated correctly but the pivot table (city_tour
) does’nt. When I was further debugging I noticed when a integer value is custom assigned (As example: $tour->cities()->attach(2);
) the code works fine. It seems there is a problem in assigning the value to the $waypoint
variable inside the query. But I can’t figure it out, help is much appreciated.
Upvotes: 2
Views: 382
Reputation: 875
You could try where('name', 'LIKE', "%$waypoint%" )..... "=" usually doesn't play well with strings unless its an exact match.
LIKE in SQL gets closest match. Use of % with LIKE:
searching for the City 'Algiers'. this would find the city
$city = 'Algiers';
City::where('name', 'LIKE', "$city" )->firstOrFail();
if you have a white space then you might get nothing
$city = ' Algiers';
City::where('name', 'LIKE', "$city" )->firstOrFail();
if you use % then the space or character is ignored.
$city = ' Algiers'; //extra space on the end
City::where('name', 'LIKE', "%$city" )->firstOrFail();
or if you want to ignore any deviations from the end of the word:
$city = 'Algier'; //with 's' missing
City::where('name', 'LIKE', "$city%" )->firstOrFail();
or you dont have to use LIKE but you make sure the $city is in the column.
Hope that helps
Upvotes: 1