I'm building a RESTful API with Laravel 5.2 and I have an AngularJS 1.5 front end. I am successfully writing services to get information but I am having troubble putting or posting anything to the database when I pass it to the API. I've tried doing some searching and but I just don't understand how to actually save data I would send the API. Here is my attempt so far:
-Service from the Factory-
addReceipt: function(request) {
return $http.post(api_url + "/rewards/receipts/add", request).then(function(results) {
console.log(results);
return results.data;
});
}
-From the Controller
$scope.submitReceipt = function() {
rewardsFactory.addReceipt($scope.model).then(function() {
console.log($scope.model);
toaster.pop({ type: 'success', title: 'Claim Submitted!', body: "Thanks! We'll take a look at your claim shortly.", showCloseButton: true });
});
};
-From Laravel API routes
Route::post('rewards/receipts/add', 'Rewards\RewardsController#addReceipt');
-From Laravel Controller
public function addReceipt(Request $request)
{
//Add the Receipt
DB::table('receipts')->insert(
['transaction_id' => $request->input('transactionID'),
'client_id' => $request->input('client_id'),
'location_id' => $request->input('location_id') ]
);
}
My Current Cors setup seems to be working out well enough for at least some traffic so I don't think that is the problem but I'm just still not sure what I'm doing wrong.
Note that $http does not send form encoded data by default, it sends application/json in request body.
I don't do any work with laravel but if you check $_POST you will see it is empty so $request->input is probably empty also.
In php you can access the response body using :
json_decode(file_get_contents('php://input')[,true/*optional to convert to array*/])
I believe that json_decode($request->getContent()) will do the same in laravel
The alternative is to use the following $http set up taken from the docs to send form encoded data
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
You can also set $http.defaults in a run block so all post or put are sent as x-www-form-urlencoded and not have to add the config to each use
Related
I have a Controller in my Laravel project called Clientecontroller, it works perfectly. Inside it, I have a method called listar() who brings me client's information.
public function listar(Cliente $cliente) {
$clientes = DB::table('clientes')
->where('documento_id', 1)
->first();
return $clientes;
}
Sure it has some troubles but my main question is, how I call this listar() function from a view with Angular or Ajax or whatever could work.
I am working in a selling system and I have to bring the client information before selecting anything else. I want to write the ID number from the clients in my view and bring the client information from my controller without reloading. But I am still stuck in the processing reaching the listar() function.
Thank you very much.
in your routes.php file add
Route::post('/cliente', 'Clientecontroller#listar');
And now use your ajax call in order to send data to /cliente the data will be sent through to your listar method in the ClienteController.
$.ajax({
type: "POST",
url: '/cliente',
data: { id: 7 }
}).done(function( msg ) {
alert( msg );
});
This question was answered, for more details head over here
1. The classical HTML approach
Let's say you have a button on your page :
<button id="call-listar">Call !</button>
You could send an HTTP Request to your Laravel application like that :
document.querySelector('#call-listar').addEventListener('click', (e) => {
// Use the fetch() API to send an HTTP Request :
fetch('/the-url-of-listar-controller')
.then(response => response.json())
.then(json => {
// Do what you want to do with the JSON
});
});
📖 You can find a very usefull documentation about the fetch() API here : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
2. Inside an Angular Component
This is an other story here, let's say you have this button in your HTML Template :
<button (click)="callListar()">Call !</button>
Inside your TypeScript, you could use HttpClientModule to send an HTTP Request to your Laravel App :
class MyComponent {
constructor(private http: HttpClient){}
callListar() {
this.http.get('/url-of-listar-controller')
.subscribe(response => {
// Do what you want with the response
});
}
}
WARNING : HttpClientModule needed !
You must import the HttpClientModule inside your AppModule or any other module of your Angular App where you want to use this component :
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [...],
imports: [HttpClientModule]
})
So I have a josn object which has an array of objects which I want to send to a react native app through https but the problem is that I get null in react native
The code of the php :
<?php
class Product {
// Properties
public $title;
public $price;
}
header('Content-Type: application/json');
$ProductList =array();
$aa=$a->{'shopping_results'};
foreach($aa as $y => $y_value) {
$product = new Product();
$product->{'title'} = $y_value ->{'title'};
$product->{'price'} = $y_value ->{'price'};
array_push($ProductList,$product);
}
echo $x=json_encode(array('listx' => $ProductList),JSON_UNESCAPED_UNICODE);// the JSON_UNESCAPED_UNICODE for the Arabic letters
?>
When I try to view the content of this json on the browser this is what I get
https://i.stack.imgur.com/gXT4X.png
The react native code
await fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// , body: JSON.stringify({ name: "tea" })
})
.then((response) => response.text()) //tried .json() got JSON Parse error: Unexpected EOF
.then((responseJson) => {
console.log(responseJson);//This prints blank
console.log("hi");
this.setState({ output: responseJson });//nothing shows
})
.catch((error) => {
console.error(error);
});
Note: I tried to receive a text from HTTPs request and it worked (The connection is fine)
You need to set HTTP headers, methods in your PHP code so as to accept requests from your react native app (basically I'm telling you to implement REST APIs). If already implemented, just make sure you are giving the correct endpoint in your react-native's fetch URL. And one more thing, when you are trying to retrieve data from the server make sure to set method: 'GET'.
If you're a beginner/ don't have prior knowledge about REST APIs, then here's a reference for you : https://www.positronx.io/create-simple-php-crud-rest-api-with-mysql-php-pdo/ I'm sure it'll give you some basic idea about your need.
I'm learning to build React JS WebApp with Laravel Back End. I have problem when try to insert data, it seems my insert function in controller is not being called whatever method I try. Here is the code;
The JS:
fetch( '/api/links/', {
method:'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(link)
})
.then(response => {
return response.json();
})
.then(data => {
//update the state of links
});
The /routes/api.php:
Route::post('links', 'LinksController#store');
The /app/Http/Controllers/LinksController.php:
public function store(Request $request)
{
$link = new Link;
$link->title = 'Hard Coded Just For Testing';
$link->url = 'http://but.still/not-inserted-to-database/';
$link->save();
return response()->json(null, 200);
}
My expectation there should be a new record in my Links table, but nothing new inserted.
What did I Miss?? Please Help.
UPDATE:
Event though I set the method to post in fetch options, it turns out when I observe in Developer tools - network tabs, it strangely change to GET method, that's why it never get to call my store function to insert data. Does anyone know what causes this?
SOLVED:
It turns out that because of extra '/' at the end of fetch URL, while in routes/api.php the URL does not have '/' at the end of it, that causing a reroute when original call to /api/links/ with POST rerouted to /api/links with GET. SO simply match the URL perfectly from the route and from the fetch, solve the problem.
I am trying to handle the push update in Angular in the view but it has been impossible for me. I know the following:
I have an array, this array is called marca1 and it receives all the objects that the get request that I make to the server and it shows in the view with ng-repeat.
When I send the post request to save a new data, it gets a response from the server that I save it in an object called pepa.
I use the push function for my fix to refresh the view, but that does not work.
Why can it be failing? How can I fix it?
This is my code:
miAppAngular.controller('marca',function($scope,$http,$location,$routeParams,configuracionGlobal){
$scope.config = configuracionGlobal;
$scope.marca1=[];
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then( function(respuesta){
$scope.marca1=respuesta.data;
});
$scope.nuevaMarca = function ( ){
$scope.newMarca={
'nombre':$scope.nombreMarca
}
$scope.pepa={};
//
$http({
url: configuracionGlobal.api_url + "/marca/nuevaMarca.php",
method: "POST",
data: $scope.newMarca,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(
function(respuesta){
$scope.pepa= respuesta;
$scope.marca1.push($scope.pepa);
$('#modalMarca').modal('hide');
}
)
}
Try to run getMarca after posting:
$scope.getMarca = function() {
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then(function(respuesta)
{
$scope.marca1=respuesta.data;
});
}
In your .then() of your post, at the end call: $scope.getMarca()
This shall update the array $scope.marca1.
The response returned after a POST is usually used for checking; whether it was a success or failure (or to return custom values from backend).
Im using Laravel 5 as an API and i have AngularJS running my frontend.
I have built the login portion of the backend that accepts the form data and responds with a json object.
My question is when i recieve the success object from the api to say that the login details are sucessfull. How do i use AngularJS to then login the user from the frontend.
AuthenticateUser.php
http://pastebin.com/PZqGCpz5
app.js
var app = angular.module('app', []);
app.controller('AppCtrl', function($scope, $http) {
$scope.login = {};
$scope.submitLoginForm = function () {
var email = $scope.login.email;
var password = $scope.login.password;
$http({
method : 'POST',
url : '/api/1.0/auth/login',
data : { email, password },
headers : { 'Content-Type': 'application/json' }
})
.success(function(data) {
console.log(data);
});
}
}
JSON Response
success: Object
message : authentication_successfull
code : 200
user_id : 1
What steps should i take from here to log the user into the frontend.
Thanks in advance
You can do this with the help of api_token approach.
First when you call a login api then create a unique token specific to user and save it database and send it in response as:
success: Object
message : authentication_successfull
code : 200
data : {api_token: some_random_key}
Then for subsequent request send that api_token in the request headers.
And server will automatically logins the user if you are using the auth:api middleware as:
Route::group(['middleware' => ['auth:api']], function()
{
// API routes here
});
For reference