Laravel Model save() & update() Not Saving - php

Laravel 5.7
Hello I have been looking through stack overflow and have tried many possible answers and have come to no conclusions.
I am updating a simple integer value in a patron table through simple checks and it is not updating the database. I have tried using save() and update() methods on the model.
There are no errors or exceptions that show up and the save() and update() methods return true.
code:
Controller Class Using the model and updating data:
$patron_coupon = PatronCoupons::where('owner',$patron_id)->where('coupon_id',$active_coupon['coupon_id'])->first();
if($patron_coupon->current_uses > $active_coupon['max_uses'])
$patron_coupon->current_uses = $active_coupon['max_uses'];
// if i echo $patron_coupon->current_uses here, it will show that this value has changed ( good )
$patron_coupon->current_uses = $active_coupon['max_uses'] - $patron_coupon->times_used;
if($patron_coupon->current_uses < 0)
$patron_coupon->current_uses = 0;
// this doesnt work
$patron_coupon->save();
// this doesnt work either
$patron_coupon->update($patron_coupon->toArray());
// if i echo current_uses here, the value goes back to what it was before being set.
Model Class:
class PatronCoupons extends Model
{
protected $table = 'patron_coupons';
protected $primaryKey = 'owner';
public $timestamps = false;
protected $fillable = ['times_used','current_uses','settings_version'];
}
Migration File:
Schema::create('patron_coupons', function (Blueprint $table) {
$table->string('owner'); // patron id that 'owns' this coupon
$table->unsignedInteger('coupon_id'); // id of this coupon
$table->unsignedInteger('current_uses')->default(0); // the amount of uses this patron has for this coupon
$table->unsignedInteger('settings_version')->nullable();// last settings version fetch
$table->unsignedInteger('times_used')->default(0); // amount of times this coupon has been used
});
Please help, I've been banging my head on my desk for hours !!!!!

You can try any of the following:
Try using static update function instead
PatronCoupons::update([
// updates here
]);
Remove your vendor folder and composer.lock file. Then run composer install to refresh your vendor file

get record
$patronCoupons = PatronCoupons::find($id);
$patronCoupons->update([
'times_used' => 'value',
'current_uses' => 'value',
'settings_version' => 'value'
]);
if your post data with the same input name then directly use
$post = $request->all();
$patronCoupons = PatronCoupons::find($id);
$patronCoupons->update($post);

Make sure that you put this code in the form because of which the error occurs
'enctype' => 'multipart/form-data'

Related

I'm getting an error when trying to save a new model with 2 fields referencing different ids in the same table

I'm new to laravel, and I've picked up the basic workflow of creating, updating and deleting database entries using migrations, models and controllers. But now I'm trying to do the same with a subscriptions table that has a subscriberId and a followeeId in it. Both of these fields reference different ids of the same table (users). This kind of task seem to require some finetuning. And I'm stuck.
Here's my code with some comments.
Subscriptions Table
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('subscriberId');
$table->unsignedBigInteger('followeeId');
$table->foreign('subscriberId')->references('id')->on('users');
$table->foreign('followeeId')->references('id')->on('users');
});
Previously, I've used another approach to foreign ids, namely the one with the $table->foreignId('user_id')->constrained() pattern, but in this particular case I need to make sure that the two foreign ids reference different users, so I went for a more verbose option.
User Model
public function subscriptions()
{
return $this->hasMany(Subscription::class, 'subscriberId');
}
Here I've added the second parameter. This seems to work.
Subscription Model
class Subscription extends Model
{
use HasFactory;
protected $fillable = [
'subscriberId',
'followeeId'
];
public function subscriberId()
{
return $this->belongsTo(User::class, 'id', 'subscriberId');
}
public function followeeId()
{
return $this->belongsTo(User::class, 'id', 'followeeId');
}
}
Here I pass additional parameters, too, although in this case I'm not so sure if these are the correct ones. But this is my best guess. If I'm not mistaken, the second parameter of the belongsTo relation is inferred from the model that is being passed in, not the model of the parent class as is the case with the hasMany relation. So in this case that would be 'id' of the users table, which would be the default here anyway, but I need the third parameter, so I explicitly state the second parameter as well. Again, I'm not sure about this combination, but that's what I was able to make of the docs. I've also used other combinations of additional parameters, and even tried getting rid of these two public functions altogether, but that won't work either.
Now, here's the controller. If I do this:
$user->subscriptions()->get();
I do get the subscriptions I want. But if I do this instead:
$user->subscriptions()->create([
'subscriberId' => 1,
'followeeId' => 2
]);
I get the 500 error. I've also tried another approach:
$newSub = new Subscription;
$newSub->subscriberId = 1;
$newSub->followeeId = 2;
$newSub->save();
return $newSub;
But still no success. I still get the 500 error when I try to save()
Please help me out.
Solution
I should have used
public $timestamps = false
in the Subscription model, and I also misunderstood the docs. The correct combo is
User Model
public function subscriptions()
{
return $this->hasMany(Subscription::class, 'subscriberId');
}
and
Subscription Model
public function subscriberId()
{
return $this->belongsTo(User::class, 'subscriberId');
}
public function followeeId()
{
return $this->belongsTo(User::class, 'followeeId');
}

unable to save foreign key into my table using laravel 5.5

i am trying to save foreign key which coming from another table into my controller method but i am unable to save this and stuch in this issue:
what i am trying to do here is there is business_id which is FK coming from business_master table:
My controller method:
$businessId = Input::get('business_id');
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business()->attach($businessId);
$page->business_id = $businessId;
$page->save();
$resultArray = ['status' => 1, 'message' => 'Page url added!', 'dataArray' => $page];
}
and my page model:
class Page extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id','page_url','page_name'];
public function business()
{
return $this->hasMany('App\Business','business_id','id');
}
error i am getting here is
BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::attach()
i desperately want to store business_id (fk) but i am unable to do that your any help will be highly appreciated!
You have an error because only instance can be attached in many to many relationsip
$page->business()->attach($businessId);
Try bussiness create()
$page->business()->create([]);
Remove the line
$page->business()->attach($businessId);
Use only
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business_id = $businessId;
$page->save();
The code will work for you.
It's good that you are using $fillable as it's help In the Eloquent ORM to avoid the mass assignment of such fields, we define the list of fields in the model under the fillable, so that when we send the array of values to model it will directly process the operation on depends upon the action like create, update, delete, etc.

Data not getting updated laravel 5.2

I'm trying to update a row in a particular table, laravel does not shows any error but value is not updating in database.
this is my update method code:
function update(Request $request){
$product=product::find($request['Id']);
$product->productName=$request['name'];
$product->description=$request['desc'];
$product->discount=$request['discount'];
$product->inventory=$request['inventory'];
$product->save();
return response()->json(['message'=>$product->productName],200);
}
I'm successfully getting all the data and I've checked that my changing the value of response json
the variable $product->productName also shows updated value as it is present after save() method but nothing changes in database.
The problem is with this piece of code as I have checked my model i.e product and its working fine as $product has value.
By default Laravel is protecting all models from mass-assignment vulnerability. So you have to specify either a $fillable (which fields can be modified) or $guarded (which fields can not be modified) property.
In your case add this to the model:
protected $fillable = [
'productName',
'description',
'discount',
'inventory',
];
Are you not trying to update this record?
Why are you using save() method, why not use update() since you are trying to set the given product with new set of values?:
$product->update();
So you can finally have (suggesting a check on if a product exists and if the update was successful - you can disregard it if you like):
function update(Request $request)
{
if(!$product=product::find($request['Id']))
{
return response()->json('Product does not exist', 404);
}
$product->productName=$request['name'];
$product->description=$request['desc'];
$product->discount=$request['discount'];
$product->inventory=$request['inventory'];
if($product->update())
{
return response()->json(['message'=>$product->productName],200);
}
return response()->json('Something went wrong', 500);
}
Hope it helps :)

Laravel Eloquent::Find() returning NULL with an existing ID

It's pretty straightforward as it's the most basic thing but I don't know what I'm missing:
Having a model called Site
I'm using Eloquent ORM, so when I call (in a controller)
$oSite = Site::find(1)
and then
var_dump($oSite);
It returns a value of NULL.
But when I check the database, the table 'sites' actually contains the following item:
id: 1
user_id: 1
name: test
In my Site model I have the following code:
use Illuminate\Database\Eloquent\ModelNotFoundException;
Class Site extends Eloquent {
protected $table = 'sites';
protected $fillable = ['user_id', 'name'];
}
Instead, if I gather the item with the following:
$oSite = DB::table('sites')
->where('id', 1)
->first();
It works and I get the correct register.
What I'm doing wrong? Which part of the documentation I didn't get?
EDIT:
Model code can be checked above.
Controller:
use Illuminate\Support\Facades\Redirect;
class SiteManagementController extends BaseController {
...
public function deleteSite()
{
if (Request::ajax())
{
$iSiteToDelete = Input::get('siteId');
$oSite = Site::find($iSiteToDelete);
return var_dump($oSite);
}
else
{
return false;
}
}
}
EDIT 2: (SOLVED)
Real reason why wasn't working:
I had originally in my model code the following:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
use Illuminate\Database\Eloquent\ModelNotFoundException;
Class Site extends Eloquent {
protected $table = 'sites';
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
protected $fillable = ['user_id', 'name'];
}
Problem was I added a 'deleted_at' column after I started the project and when I applied migrations, I didn't have softdeleting enabled.
Obviously, I did a second error, forgetting to enable 'deleted_at' to be nullable, hence all inserts went had a wrong timestamp (0000-00-00 ...).
Fix:
Made nullable 'deleted_at' column.
Set all wrong 'deleted_at' timestamps to NULL.
Check you are getting Input::get('siteId') correctly. if you are getting it then try to convert it into integer i.e
$iSiteToDelete = intval(Input::get('siteId'));
You're not returning your model.
var_dump prints output and returns nothing.
do this instead:
dd($oSite); // stands for var_dump and die - a helper method
and even better, simply return the model:
return $oSite; // will be cast to JSON string
In my case I was using a custom query with the DB facade. I neglected to skip records that have a deleted_at in my DB query. When showing all the records, it worked with IDs that had already been deleted, so methods like find that if they were considering the deleted_at, did not find the record.
Layer eight.
For the future if you encounter a similar problem you can check what SQL queries laravel is sending to the database.
Todo so just enable query logging by using DB facade:
\DB::enableQueryLog();
Before sending request to database.
Then after using find() or get() you can get all requests by:
\DB::getQueryLog();
You can getQueryLog into dd() function and see what database queries were made.

Laravel 4 eloquent Mass assignment error in fillable

I'm currently studying eloquent of L4 and I encountered this mass assignment. I'd follow the instructions and I know you need to setup your $fillable to use the create method but I am still receiving a blank row in the database. here's my code:
MODEL:
class User extends Eloquent
{
protected $fillable = array('email','pwd','active','name');
}
CONTROLLER:
$user = new User;
$add = array(
'name'=>Input::get('custname'),
'active'=>1,
'pwd'=>Hash::make(Input::get('pwd')),
'email'=>Input::get('email')
);
return var_dump($user->create($add));
I also did:
CONTROLLER
$add = array(
'name'=>Input::get('custname'),
'active'=>1,
'pwd'=>Hash::make(Input::get('pwd')),
'email'=>Input::get('email')
);
return var_dump(User::create($add));
But still the same result.
There was a bug causing this, see https://github.com/laravel/framework/issues/1548
Should be fixed now, run composer update to get the newest version of laravel/framework
Yes with new version you can use public or protected keywords.
Simple use this :
protected $fillable = [‘email’, ‘pwd’,’active’,’name’];
You can also specify table name if you are working with other Model like this :
public $table = ‘users’
This is working fine after run composer update on the root of project directory.

Categories