How do I call a function from Angular controller to Laravel Controller? - php

First off, I'm pretty new with Laravel+Angular which basically why I'm here.
I have this function delete from my Angular controller that uses $http.delete() to call the Laravel controller.
$scope.deleteJob = function(index) {
$scope.loading = true;
var job = $scope.jobs[index];
$http.delete('/api/job/' + job.jobId)
.success(function() {
$scope.job.splice(index, 1);
$scope.loading = false;
});;
};
With this route I should get to the Laravel controller:
Route::resource('api/job','ApiJobController');
Which i have defined a function to delete from my eloquent DB
public function destroy($id)
{
App\Job::destroy($id);
}
I don't know what I miss but everytime I invoke deleteJob(index) I get a Server Error.
DELETE http://localhost:8000/api/job/20 500 (Internal Server Error)
I tried using /api/job/destroy/, still getting 500

Try with this route
Route::get('/api/job','ApiJobController#destroy');
Or you can use
$http({
method: 'DELETE',
url: '/api/job/' + job.jobId
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Try this.
App\Job::find($id)->delete();

Related

Post form data to php script using axios

I'm trying to send the form data to a php script using axios.
Is the syntax of axios correct?
How can I view the data sent via the post method?
I just started programming in vuetify and php, so I need a little help
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://localhost/index.php/',{
name : this.name, user : this.username
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
},
}
in the php file there's :
<?php
require_once 'limonade.php';
$data = $_POST;
dispatch('/api/', 'test1');
function test1()
{
return 'Hello';
}
run();
Your php only acts when it's a GET Call, limonade's dispatch() is for GET only.
In your php you are creating a GET endpoint on the /api/ url that will execute the test1 function. Meaning when you call /api via get, you will get Hello as answer.
if you want that to be POST (without touching your javascript) the php should be something like:
# '/' because you are calling to http://localhost/index.php/ it could be '/whatever' if you call http://localhost/whatever (assuming you have configured everythign as limonade recomends)
function test2()
dispatch_post('/', 'test2');
{
return 'Hello via post';
}

Ajax GET request is empty despite correct query string parameter

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

AngularJS $http.get executing PHP to delete file. IE still finds file after deleting?

This is on Internet Explorer only.
I have a factory that provides notifications for my app.
The input for those notifications is a file (qc.sta) that is created automatically by a third party software and is dropped in a specific folder.
Whenever that file exists, a new notification is added to the app.
My mechanism would be to get the data from that qc.sta file and then delete it after collecting the data.
To delete a file I need to execute a PHP that deletes the file, but this seems to have to be done inside a $http.get, so I end up with an $http.get inside another $http.get.
What happens is that the notifications (triggered on a $interval inside the controller) keep popping up continuously, despite the file being deleted.
My factory is as below:
myApp.factory("qcSTA", function ($http, $q) {
return {
apiPath: "data/qc.sta?rnd=" + new Date().getTime(), //randomizing request to prevent caching
getNotifications: function () {
//Creating a deferred object
var deferred = $q.defer();
//Calling Web API to fetch notifications
$http.get(this.apiPath, { headers: { 'Cache-Control': 'no-cache'} })
.success(function (response) {
//Passing data to deferred's resolve function on successful completion
//Does whatever needs to be done to the response before passing it on
function deleteFile() {
$http.get("deleteFile.php");
return false
};
deleteFile();
deferred.resolve(JSON.parse('{"item" : "' + response.itemNumber + '", "description" : "' + response.desc + '"}'));
})
.error(function () {
//Sending a friendly error message in case of failure
deferred.reject("An error occured while fetching items");
});
//Returning the promise object
return deferred.promise;
}
}
});
And my controller:
myApp.controller("notificationController", function ($scope, $location, $interval, $q, qcSTA) {
function getNotifications() {
qcSTA.getNotifications()
.then(function (data) {
$scope.notifications.push(data);
},
function (errorMessage) {
$scope.error = errorMessage
});
}
}
How can I ensure the notification only pops up once rather than going in circles?
Could this be cache related?
If I refresh the browser, it won't get more notifications, it's like it finally detects the qc.sta file isn't there anymore.

How to call custom action in controller(laravel) using AngularJS

I am using laravel 5.
I have a custom action in my controller. By custom I mean it is not used by the resource object in angular. The following is the code of my controller.
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
This is my service code in the angular script.
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
Now, the query() here will send the request to the index method in the laravel controller. How will I access the extras() action in the getExtras() method?
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '#id',
param: '#param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController#custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController#extras');
I got what I wanted using $http.
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
But, that would be nice if anyone suggest me how to do it with Serviceb.query().$promise.then.

Categories