laravel 5.2 ->update not works - php

in my controller i have $data['column1'] = 1; It updates database with $x->update($data);
Why if add $data['column2'] = 2; it ignores second parameter? I checked with dd($data); and it shows both parameters.
I removed default value, which being inserted by mysql, but that did not help.

Make sure that column2 is listed in the $fillable property of your model. Only attributes that are listed there can get a value assigned with your model's create/update methods.

Related

Laravel fill not setting component property

I have run into an issue with Laravel that hopefully someone could help explain. The fill command is not setting the properties of the model, and instead can only be used to save them to the database with the ->save() function. Is there a way to do fill where it actually sets the properties of the model from an array.
Example of problem below.
$comment = new comment();
$comment->fill(['name' => 'Bob']);
echo($comment->name); // Gives null/error.
$comment = new comment();
$comment->name = 'Bob';
echo($comment->name); // Gives Bob.
The reason is name filed is not fillable in comment model .To Solve this issue you have to add fillable for that field in comment model
protected $fillable = [
'name',
];
If you try to access non fillable field then it will return null.
If don't want to add it in fillable then you can use forceFill.
forceFill: Fill the model with an array of attributes with force mass assignment.
$comment = new comment();
$comment->forceFill(['name' => 'Bob']);
echo($comment->name);
Yes, you need to use fillable property of the model and need to add name inside fillable array. That's the recommended way to do it.
As suggested by John Lobo's answer, You can forcibly override that mechanism using forceFill or forceCreate.
Both ignores fillable property in the model. It may possible that you may have a column like is_admin and you do not want to update it but force will do it.
Notes :
The main problem with forceCreate or forceFill, is that we have to manage the foreign key assignment manually.
forceFill will do fill (properties) only. You need save method call to save the actual record while forceCreate will do fill (properties) and Save both together.

Insert data into two columns of a table in Laravel Controller using sql

I have been trying to insert data using query into two columns of a table but there's something missing that its not sending data in the other column named booking_code.
It is inserting the booking_id into the table but not booking_code.
Here is the controller:
public function store(CreatePaymentRequest $request)
{
$input = $request->all();
$booking_id = $request->booking_id;
$booking_code = Booking::find($booking_id)->booking_code;
$this['booking_code'] = $booking_code;
$payment = $this->paymentRepository->create($input);
Flash::success('Payment saved successfully.');
return redirect(route('admin.payments.index'));
}
Please have a look at the Relevant Documentation Pages
You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
That means that you have to set, in Model, which fields you will allow to be "mass-assigned".
In your case, it will looks something like
class Booking extends Model
(...)
{
protected $fillable = ['booking_code', (...)];
}
(...)
In the code you provided though, I can't see how you build an $input variable so maybe the issue is there? Maybe it's just some typo.

Laravel Virtual Columns fail to save

I added a couple of virtual columns to my database tables using Laravels virtualAs column modifier:
$table->decimal('grand_total')->virtualAs( '(total_value + (total_value*tax_rate))');
Basically it keeps a mysql virtual column that automatically calculates the grand total based on the total and tax rate stored in another column.
However, Laravel does not seem to play nice with virtual columns at all. When saving a record, it attempts to INSERT or UPDATE the virtual column, which is obviously not allowed in mySQL. I could not find a way to configure in the Eloquent model which fields are actually written to the database on an update or insert.
I've tried adding the field to the models $hidden, and $appends but nothing seems to work.
Looking at the Laravel Source code for an insert (https://github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Eloquent/Model.php#L733), it seems to just insert whatever attributes are in $this->attributes. When the record is read from the database the grand_total field is read from the table and set as an attribute and then it is tried to be written again once the record is saved.
Is there any way to get this Laravel to stop trying to save columns that are virtual?
Here's a quick trait I wrote to solve your problem that will filter fields residing in the $virtualFields property before saving. It requires a select (refresh) after the save to get the new value for the virtual field. If you don't need to query this virtual field, I'd highly recommend you look into a mutator instead.
trait HasVirtualFields
{
public function save(array $options = [])
{
if (isset($this->virtualFields)) {
$this->attributes = array_diff_key($this->attributes, array_flip($this->virtualFields));
}
$return = parent::save($options);
$this->refresh(); // Refresh the model for the new virtual column values
return $return;
}
}
class YourModel
{
use HasVirtualFields;
protected $virtualFields = ['grand_total'];
}

How to add value of guarded fields in database

I am using laravel 5.3 and in my custom model, I have some guarded fields like following.
protected $guarded = ['id', 'tnant_id', 'org_id', 'fac_id', 'slug', 'created_at', 'updated_at', 'deleted_at'];
Now When I try to add record using following.
CUSTOM::create(['tnant_id'=>123]);
It returns me following error.
Field 'tnant_id' doesn't have a default value.
Setting field default value in table will not work because each time I am passing value and it is giving error for all guarded fields.
So how I can add guarded fields value in database? In update query, It is allowing to update but on create it gives error.
You simply can't. Model::create(array $attributes = []) is using method fill(array $attributes = []), which, we may say, filter out all guarded attributes, so they will not be assigned. So in point of creation tnant_id will be null.
I come up with two ways of doing this:
A
create a new model instance
set your attribute
save (persist) it to dabase;
So:
$model = new Model;
$model->tnant_id = 123;
$model->save();
B
This is more likely update than create, but, might be useful for you.
Change your DB schema to allow null values for your attribute or put default value.
create model using Model::create()
set attribute & update.
So:
Assuming you are using migrations, in your migration file use:
Schema::create(..
$table->integer('trant_id')->nullable();
//OR
$table->integer('trant_id')->default(0);
...);
Note: It's hard to say which one is more suitable for you use-case, but I see your attribute is called trant_id, which is some form of relation I guess, so I suggest you to take look at Eloquent's relationship, which might be a better answer.

How to create a new row based on custom value ID in laravel 4.2

Am having a table with id as primary key not auto increment, I need to push the custom value as an ID. I tried with firstOrNew() and findOrCreate() and create() by pushing the ID as an argument like
$var_id = '99';
$var = Table::findOrCreate(['id'=>$var_id]);
return $var;
But its creating new row with 0 as ID. Can any one please suggest me how to create ID with 99.
Thanks
Did you create your table manually or through a migration? Make sure your id is set to "auto-increment" on your table. If you create through a migration it would look something like this $table->increments('id');
Try laravel query builder its flexible to use.
DB::table('tablename')->insert(
array('id' => '99'));
For more help check this link out
Laravel 4.2 query builder
I guess you're code has a small typo, in your case you probably want to use firstOrCreate or findOrNew.
Either way, by default all model attributes are guarded.
Add id to your model fillable array, like so:
protected $fillable = ['id']; // perhaps more ?
And try again.

Categories