Search code examples
phpangularjslaravel-forge

Laravel 4 AngularJS remove record from database


I've been working on a small app that uses Laravel 4 as the backend with AngularJS as a starting point (mainly to learn angularjs).

The idea is that I can add bookmarks via a form and have these show up in a searchable table. I've got it working where I can post to the database and save the records. The following does that job perfectly for my needs.

    $scope.addLink = function () {

    var link =  {
        title: $scope.newTitle,
        address: $scope.newAddress,
        type: $scope.newType
    };

    $scope.links.push(link);

    $http.post('bookmarks', link);
};

However, I can't work out how to delete a row. Well, I can remove it in the table but not from the database using routes. I have got a ng-click function that removes the row from the table using splice but don't know how to send the details to the Laravel route to remove from the database. So far I have this:

    $scope.remove = function ( idx ) {
    var link = $scope.links[idx];
    $scope.links.splice(idx, 1);

    $http.delete('removemark/{link.id}');
    };

Clearly the $http.delete is not set up correctly but not sure how to do it.

I have the route as this:

   Route::delete('removemark /{id}', function($id)
   {
     Bookmark::destroy($id);
    });

But this isn't working. Hopefully some one can point me in the next direction.


Solution

  • you need to build the url string yourself.

    $scope.remove = function ( idx ) {
        var link = $scope.links[idx];       
    
        $http.delete('removemark/' + link.id).success(function(response){
            /* should validate response and then remove from array */
            $scope.links.splice(idx, 1);
        }).error(function(err){
           /* do something with errors */
        });
    };
    

    I would suggest you leave the item in the array until you have confirmed delete from server response and then remove it from array.

    Use your browser console network tab to inspect requests. You likely would see a 404 status with what you had and would give you clues where things weren't quite right