500 internal server error, http post by angularjs - php

I try to do ajax using angularjs but I get 500 internal server error in console.
angular
$scope.submit = function(){
$http.post('shop', {'order_list': JSON.stringify($scope.order_list)})
.success(function(data) {
console.log(data);
});
}
Laravel's Controller
public function addtocart(){
OrderList::unguard();
$order_list_input = json_decode(Input::get('order_list'));
$order_list = new OrderList;
$order_list->order_id =1;
$order_list->product_id = $order_list_input->product_id;
$order_list->amount = $order_list_input->amount;
$order_list->total_cost = Prod::find($order_list_input->product_id)->price * $order_list_input->amount;
$order_list->save(); //works when I comment this line out.
var_dump($order_list_input);
}
I don't get it. I just comment out that line and it works.
Laravel's Model
class OrderList extends Eloquent
{
protected $table = 'order_lists';
protected $fillable = array('order_id','product_id','amount','total_cost');
public function order_list_attribute() {
return $this->hasMany('Order_list_attribute');
}
public function product(){
return $this->hasOne('Prod');
}
}
Thank's for your help :D

Related

Laravel get whole database table with its associates

Is there the possibility to get whole database's table with it's associates?
My example
class Gambler extends Model
{
use HasFactory;
public function horse()
{
return $this->belongsTo(Horse::class, 'horse_id', 'id');
}
}
I am fetching data of Gamblers with axios, which is being returned with this code in controller
public function getGamblers () {
echo Gambler::all();
}
However I would like to get all associated Horses as well. I can get one pretty easy just like this
public function getGamblers () {
echo Gambler::find(1)->horse;
}
but maybe there is possibility to do something like this, which in my case does not work
public function getGamblers () {
echo Gambler::all()->horse;
}
You should use return in Controllers, not echo.
Because you are using axios, a JsonResponse will be more appropriate:
public function getGamblers () {
return response()->json(Gambler::all(), 200);
}
Gambler::all() will return a Collection of Gambler.
On frontend, loop over the data you get from Laravel:
let gamblers = [];
axios.get('/your-get-gamblers-url')
.then(function (response) {
gamblers = response.data;
})
gamblers.forEach(gambler => console.log(gambler))
If for some reson you need to do something with each Gambler in php, you can loop over the collection like this:
$gamblers = Gambler::all()
foreach($gamblers as $gambler) {
//$gambler->horse
}

Laravel 5.8 Likes system with AJAX Post Request Not Working

I am building a Like system for my recipe application in Laravel and I am not able to get my AJAX POST request to function. It just simply isn't hitting my controller, so I am not able to store any likes.
I have a relationship between three models, Like, User, Recipe.
I have an individual likes table in my DB. The code is the following:
My Models
Like
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Like extends Model
{
protected $table = 'likes';
// Get all of the recipes that are assigned this like
public function user(){
return $this->belongsTo('App\User');
}
public function recipes(){
return $this->belongsTo('App\Recipe');
}
}
User
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function recipes(){
return $this->hasMany('App\Recipe');
}
public function likes(){
return $this->hasMany('App\Like');
}
}
Recipe
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recipe extends Model
{
//Table Name
protected $table = 'recipes';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
public function category(){
return $this->belongsTo('App\Category');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function likes(){
return $this->hasMany('App\Like');
}
}
AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Likes AJAX
var recipeId = 0;
$('.like').on('click', function(event) {
event.preventDefault();
var isLike = event.target.previousElementSibling == null;
recipeId = event.target.parentNode.parentNode.dataset['recipeid'];
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, recipeId: recipeId},
success: function(data){
console.dir(data);
}
})
.done(function() {
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this post' : 'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this post' : 'Dislike';
if (isLike) {
event.target.nextElementSibling.innerText = 'Dislike';
} else {
event.target.previousElementSibling.innerText = 'Like';
}
});
});
Controller Method
public function likeRecipe(Request $request){
$recipe_id = $request['recipeId'];
$is_like = $request['isLike'] === 'true';
$update = false;
$recipe = Recipe::find($recipe_id);
if (!$recipe) {
return null;
}
$user = Auth::user();
$like = $user->likes()->where('recipe_id', $recipe_id)->first();
if ($like) {
$already_like = $like->like;
$update = true;
if ($already_like == $is_like) {
$like->delete();
return null;
}
} else {
$like = new Like();
}
$like->like = $is_like;
$like->user_id = $user->id;
$like->recipe_id = $recipe->id;
if ($update) {
$like->update();
} else {
$like->save();
}
return null;
}
I'm getting various HTTP errors thrown at me as I mess with the AJAX file, but it is never working. Please help! Thank you in advance!
In this kind of situation. You need learn how to debug properly for ajax request. There are thousand reason for return 500 error.
1st step: make sure your ajax function hit your url properly. Make a simple method and dd() something.
public function likeRecipe(Request $request){
dd('Yes! it working !');
}
Go to your browser right click and Inspect then go to Network tab then you can see your request. Click on your request then look for response tab.There you can find exactly what happened.
405 means your likeRecipe function not running at all and 500 means there is any response error so try remove some of your code from likeRecipe function try again for example your first try could be:
public function likeRecipe(Request $request){
return null;
}

Laravel - "Method Illuminate\\Database\\Query\\Builder::recipes does not exist

I've looked at a few similar issues on SO, but I can't work out why recipes is being called?
I'm building a recipes website, and the user can create tags, create a recipe, create ingredients which are assigned to the recipe, and will be able to create steps which use the ingredients.
The following are my models:
Ingredient.php
class Ingredient extends Model
{
protected $touches = ['recipes'];
public function recipes(){
return $this->belongsToMany('App\Recipe', 'recipe_ingredients', 'ingredient_id', 'recipe_id');
}
public function step(){
return $this->belongsToMany('App\Step', 'step_ingredients');
}
}
Recipe.php
class Recipe extends Model
{
public function ingredients(){
return $this->belongsToMany ('App\Ingredient', 'recipe_ingredients', 'recipe_id', 'ingredient_id');
}
public function tags(){
return $this->belongsToMany('App\Tag', 'recipe_tag');
}
public function user(){
return $this->belongsTo('App\User');
}
public function steps(){
return $this->hasMany('App\Step');
}
}
Step.php
class Step extends Model
{
protected $touches = ['recipes'];
public function recipe(){
return $this->belongsTo('App\Recipe');
}
public function ingredient(){
return $this->belongsToMany('App\Ingredient', 'step_ingredient');
}
}
The following is my StepsController which I'm saving to from my steps/create.blade.php file via an Ajax submit with jQuery.
use Illuminate\Http\Request;
//use Session;
use App\Recipe;
use App\Tag;
use App\Step;
use App\Ingredient;
class StepsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create($recipe_id)
{
$recipe = Recipe::find($recipe_id);
return view('steps.create')->withRecipe($recipe);
}
public function store(Request $request)
{
$step = new Step;
$step->recipe_id = 2;
$step->step_no = 2;
$step->is_prep = 1;
$step->duration = '00:14:01';
$step->method = 'test';
$step->save();
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
'ing' => json_decode($request->ingredients),
'desc' => $request->description
] ;
return response()->json($data);
}
}
I'm using static values for the new Step to make sure that it writes to the db correctly, and it is.
If I comment out writing the step to the db, and just leave the $data array and return response... then it works fine, and I get the success response returned to the view.
When I include it, I get the error in the console:
[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (steps, line 0)
"message": "Method Illuminate\\Database\\Query\\Builder::recipes does not exist.",
But I'm not sure where the recipes method is being called?! I think it has something to do with my relationships in the model?
Any insight would be extremely appreciated.
Not sure if it's required, but the following is the part of my script that I"m using so submit data with Ajax.
$("#addStepNew").click(function() {
var step_ingredients = JSON.stringify(stepIngredients)
var step_description = $('#stepDescription').val();
// var prep_step = $('input[name=prepStep]:checked').val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: {ingredients: step_ingredients, description: step_description},
dataType:'json',
url: "{{ route('steps.store', ['id' => $recipe->id]) }}",
success: function (data) {
$("#ajaxOutput").html('<code>Description output: '+data.desc+'</code>');
$.each(data.ing, function (key, value) {
$("#ajaxOutput").append('<br><code>'+value.ingredient_name+'</code>');
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
});
It looks like it's the protected $touches = ['recipes']; from the Step model.
I guess it's trying to update a recipe that it's associated to, but that isn't being defined with a recipe_id.

Laravel Model Events don't fire

I have a model with this code:
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Intervention extends Eloquent {
use SoftDeletingTrait;
protected $fillable = array('start_date','stove_id','description','operation_mode','store_id','user_id','intervention_status_id','code');
public function operations()
{
return $this->hasMany('InterventionOperation');
}
public function store()
{
return $this->belongsTo('Store');
}
public function stove()
{
return $this->belongsTo('Stove');
}
public function user()
{
return $this->belongsTo('User');
}
public function statues()
{
return $this->hasMany('InterventionStatus');
}
then the boot
public static function boot()
{
parent::boot();
static::creating(function($intervention)
{
exit("creating");
});
static::created(function($intervention){
exit("created");
});
static::updating(function($intervention)
{
exit("updating");
});
}
the controller:
$intervention = new \Intervention(\Input::all());
$status = \Status::find(\Input::get('status')['id']);
$interventionStatus = new \InterventionStatus();
$interventionStatus->change_status_date = new \DateTime();
$interventionStatus->status()->associate($status);
$interventionStatus->description = "";
$user = \Auth::user();
$store = $user->store;
$intervention->store()->associate($store);
$intervention->user()->associate($user);
$intervention->request_date = new \DateTime();
$intervention->save();
...
but when save model, creating callback is not call.
I have try put exit("test") after parent::boot(); and exit is triggered.
If I put event's code in app/start/global.php it work.
I have try use the code in another model and work.
I do not know why it does not work.
Resolved:
I recreated the database and now everything works. Probably, in the various attempts to save, some relationship was skipped.
Thank you all for the help!
I think this has something to with the namespaces and registering the correct class in the event. Let's hack the source code a bit :)
In: /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php
Add:
public function getAllEvents()
{
return array_keys($this->listeners);
}
And call/dump Event::getAllEvents();
Try this for both cases (boot in the model and in the global.php) and compare.

Laravel4 one-to-one relationship is not loaded when in testing environment

Im currently facing this strange behaviour.
<?php
// Models
class User extends \Eloquent {
protected $table = 'user';
public $timestamps = FALSE;
public function credit() {
return $this->hasOne('Credit', 'uid');
}
}
class Credit extends \Eloquent {
protected $table = 'user_credit';
public $timestamps = FALSE;
public function user() {
return $this->belongsTo('User', 'uid');
}
}
// Service
function doThings() {
// This is always working
$credit = Credit::where('uid', $user->id)->first();
// This doesn't work in test environment, but it does outside of it, i.e. in a route
// $credit = $user->credit;
if (empty($credit)) {
$credit = new Credit();
// Set some fields... then save.
$credit->foo = 'bar';
}
$user->credit()->save($credit);
}
// Test
Service::doThings(); // <--- works as expected the first time
Service::doThings(); // <--- fails, trying to save a new record instead of updating.
// In a test route
Route::get('/test', function() {
$user = User::find(1);
Service::doThings(); // <--- works as expected
Service::doThings(); // <--- works as expected
Service::doThings(); // <--- works as expected
return 'test';
});
Problem is that when accessing the credit model via the $user->credit, in the testing environment the model is not loaded and NULL is returned regardless the presence of the item inside the database.. It works when explicitly loaded, using Credit::find().
Outside the testing env, things works as expected.
Any hint?
In your class
class User extends \Eloquent {
protected $table = 'user';
public $timestamps = FALSE;
public function credit() {
return $this->hasOne('User', 'uid');
}
}
You should use (to make a one to one relation between User <-> Credit using a custom key uid)
class User extends \Eloquent {
protected $table = 'user';
public $timestamps = FALSE;
public function credit() {
return $this->hasOne('Credit', 'uid'); // <---
}
}
So, you can query like
$credit = User::find(1)->credit;

Categories