Save issue in Laravel - laravel

Table Structure:
1 ID int(11) AUTO_INCREMENT
2 filename varchar(11) latin1_swedish_ci
3 status int(2)
4 type int(11)
5 created_at timestamp
6 updated_at timestamp
Route::get('/verify1/{data}',function($data){
$task= FileLocation::where('ID',"=",$data)->first();
$task->status = 1;
$task->save();
});
Problem: I tried to return $data. It displays $data=1. I have ID=1 in the table too. Why it doesn't save? Could you please help. This issue screws up my head. I am new to laravel. Thank you.

in FileLocation model class add protected $fillable = array('status');. Mass Assignment will not allow to update this data untill laravel will not know it is ok, to update it. If all data can be changed than add protected $guarded = array(); This and more info on this sub. can be found here
In shortcut:
Once model is created, some attributes, are protected by laravel. This is in case of sensitive data, like: 'id', 'created_at' etc. By default all attributes are protected. It can be change in two ways: (white or black)list. These are protected $fillable or protected $guarded arrays that contain attributes to care of.

Related

How to read guarded id field of model?

In laravel 6 project there is a model with guarded id field:
class Customer extends Model implements Transformable
{
use SoftDeletes, RevisionableTrait, TransformableTrait;
protected $table = 'customers';
protected $guarded = ['id'];
and creating new customer with factory, I see null id field value:
$NewCustomer = factory(Customer::class)->make();
\Log::info( '-99 $NewCustomer->id ::' . print_r( $NewCustomer->id, true
) ); // THIS value is null
How to read id value of $NewCustomer ?
Thanks!
Make only creates an object but does not save it to the database. Therefore you do not get an id.
The primary key will be auto-incremented in the database, so you only know the id after you save the object.
Creating Models
If you want to save automatically you can also directly use the save function:
$NewCustomer = factory(Customer::class)->create();
This work the same as:
$newCustomer = factory(Customer::class)->make();
$newCustomer->save();
Persisting Models
Also guarded is only a security feature for mass-assignment and prevents saving the id row on those.
Mass Assignment

Adding two created_at on one insert

I want to add another created_at column on the database columns for reference.
I want to have a created_at and created_at1 at the same time.
This is what I have in my Model:
const CREATED_AT = 'created_at1';
protected $dates = [created_at, created_at1];
But I'm receiving this error: Field 'created_at' doesn't have a default value.
You do not need to add casting to the created_at since Laravel has already done it for you.
You need to add inside the string like
protected $dates = ['created_at1']
If you want to set the created_at1 when a new model is created, you can add Model Events.
Inside your model,
protected static function boot(){
parent::boot();
static::creating(function($model){
$model->created_at1 = Carbon::now();
});
}
Inside controller
$model = Model::create([
...
]);
Now it will set created_at and created_at1
For the insert, you have to manually save the value to the created_at1 because it will not reflect the model event.
Model::insert([
...
'created_at1' => Carbon::now()
]);
You might not be passing value to created_at column while inserting data. Please do check. If this is not the case please do provide more information on your problem.

How does laravel/lumen dateformat 'U' actually works?

I'm not able get the timestamps with dateformat 'U' working in lumen.
In migration:
$table->timestamps();
In Model:
protected $dateFormat = 'U';
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
public function getDateFormat()
{
return 'U';
}
Insert row from controller:
$model = new ApiKey;
$model->random= rand();
$model->name = $name;
$model->scope = $scope;
$model->save();
It does insert the row in the database but with 0000-00-00 00:00:00 values for created_at and updated_at columns.
Also, while retrieving a model via toArray or toJson it thrown exception:
I want lumen to autoupdate the timestamps and retrive timestamps as unixtimestamp format i.e. number of seconds from 1st Jan 1970.
Also, $table->timestamps() didn't create deleted_at column. What do I need to do get this column created via laravel.
Is there any other option than $table->timestamp('deleted_at');?
I've found a solution bay changing timestamps columns to int. But I want the things to be done in laravel way.
Unix timestamps are integers, not compatible with SQL datetime/timestamp fields. If you want to use unix timestamps, use integer field types for storage.
The timestamps() method only creates created_at and updated_at, soft deletes are not enabled by default. This method should not be used if you want integer storage.
If you only want to change the output format when serializing data, use casting:
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime:U',
];
This is likely caused by the fact that Laravel/Lumen created the date/time columns as the type timestamp not int so you're trying to save wrong type of data in the field, causing the 0000-00-00 00:00:00.
This would also cause the carbon issue as you are trying to createFromFormat with the wrong format compared to the content.
You can use $table->integer('deleted_at'); in your migration to create a deleted_at column.
TL;DR:
Manually create your date time columns with $table->integer('updated_at').
<?php
namespace App\Traits;
use Illuminate\Support\Carbon;
trait sqlServerDateFormat
{
public function fromDateTime($value)
{
return Carbon::parse(parent::fromDateTime($value))->format('d-m-Y H:i:s');
}
}

$fillable and create() not working

I've just installed new laravel project. After that, I created new Model but when I use create() function, it just show me that my new rows has been duplicated.
This is my code:
protected $fillable = ['id', 'setting_name', 'expected_type', 'default_val', 'modified_val'];
// protected $guarded = ['created_at', 'updated_at'];
function test() {
$input = ['setting_name' => 'Test',
'expected_type' => '123',
'default_val'=>'123',
'modified_val'=>'123'];
// dd($input);
//both next two lines do not working
Setting::create($input);
return Setting::firstOrNew($input);
}
I checked the error :
"Integrity constraint violation: 1062 Duplicate entry '' for key 'setting_name' (SQL: insert into settings (updated_at, created_at) values (1474452834, 1474452834))"
What i did wrong ?
At the end of the day, I realized that I created __constructor for my model, that why I could not create object normally.
I removed that constructor and it works well. :D
The error says you're trying to insert row with setting_name which is already exists in a table and you have unique constraint for this column.
So, make sure you're inserting this row only once and there is no any other row with the same setting_name value.

Laravel 5, can't get the ID of the just saved model, when using UUID

I'm using Laravel Eloquent for my posts table and using the UUID for my table's primary key. But after saving the model I can't get the ID from it, although all the values are correctly inserted in database.
$post = new App\Post();
$post->uuid = \Webpatser\Uuid\Uuid::generate();
$post->save();
dd($post->uuid); //return null or 0
Adding accessors or using $post->getKey() could not solve my problem.
According to Laravel API documentation, Eloquent Models have a boolean property $incrementing which indicates if the IDs are auto incrementing. To use UUIDs in our models we have to set this variable to false like this:
public $incrementing = false;

Resources