Anonymous
Anonymous

Reputation: 107

Submitting post information from AngularJS to Laravel REST API

I followed the following tutorial (https://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785) to create a REST API with Laravel. Here we're creating a new Url which gets two inputs: a url and description and stores it to a database.

public function store()
{
    $url = new Url;
    $url->url = Request::get('url');
    $url->description = Request::get('description');
    $url->user_id = Auth::user()->id;

    $url->save();

    return Response::json(array(
        'error' => false,
        'urls' => $urls->toArray()),
        200
    );
}

In trying to teach myself AngularJS, I've been trying to connect this REST API with an AngularJS front end. Here's my form:

<form data-ng-controller="formController">
    <p>Store a URL To Read Later:</p>
    <div class="form-group">
        <input class="form-control" type="text" placeholder="Enter URL here" data-ng-   model="newurl" />
    </div>

    <p>Description:</p>
    <div class="form-group">
        <input class="form-control" type="text" placeholder="Enter a brief description" data-ng-model="newdescription" />
    </div>

    <div class="form-group text-right">
    <button class="btn btn-success" data-ng-click="submitUrl()">Add To List</button>
    </div>
</form>

The data-ng-click is calling the submitUrl function which I have defined in the FormController.

function formController($scope, $http) {
    $scope.submitUrl = function() {
        var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
        $http.post("http://readitlater.loc/api/v1/url/", data )
    }
}

I guess I'm puzzled as to how to get the input data to the public function store() and what kind of data it's expecting. Thanks for your time.

Upvotes: 0

Views: 5056

Answers (2)

Anonymous
Anonymous

Reputation: 107

I figured it out. Rewriting like this, solved the problem.

 function formController($scope, $http) {
    $scope.submitUrl = function() {
        var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
        $http({
            method: 'POST',
            url: 'http://readitlater.loc/api/v1/url/',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},

            data: $.param(data)
        });

Upvotes: 2

kozlice
kozlice

Reputation: 724

AngularJS sends POST requests with application/json type & JSON body by default. I'm not familiar with Laravel, but looks like using Input instead of Request is what you need: http://laravel.com/docs/4.2/requests#basic-input

Upvotes: 0

Related Questions