How to read guarded id field of model? - laravel

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

Related

how to filter related tables by date in Laravel?

I have 2 related tables and I need to filter the date of a table by month
My first table have the following fields: Id_agendamien_persona , Id_agendamiento, id_persona
The second table have the following fields: Id_agendamiento, fecha
so I need to filter fecha in the second table,
Mi controller
public function listar(){
$contactos = Contacto::pluck('completo','id_contacto');
$contacto_x_agendamientos = Contacto_x_Agendamiento::all();
array_add($contactos,0,"::Seleccione::");
return view('agendamiento.listar')->with(compact('contacto_x_agendamientos','contactos'));
}
My model
first table
class Contacto_x_Agendamiento extends Model
{
protected $table = "contacto_x_agendamiento";
protected $primaryKey = 'id_contacto_x_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function Agendamiento(){
return $this->hasOne(Agendamiento::class,'id_agendamiento','id_agendamiento');
}
}
second table
class Agendamiento extends Model
{
protected $table = "agendamiento";
protected $primaryKey = 'id_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function scopeMes($query){
return $query->whereMonth('fecha_agendar','=',date('m'))->get();
}
}
View
<td>{{$contacto_x_agendamiento->Agendamiento->Mes()->fecha_agendar}}</td>
error
Property [fecha_agendar] does not exist on this collection instance.
The issue here, is that you're trying to fetch the property of an Agendamiento model from a Collection that you're getting back as a result.
Here you have two choices. You either get just one model, by using ->first():
echo $contacto_x_agendamiento->Agendamiento->Mes()->first()->fecha_agendar;
Or you iterate the Collection and print each fecha_agendar property:
foreach ($contacto_x_agendamiento->Agendamiento->Mes()->get() as $agendamiento) {
echo $agendamiento->fecha_agendar;
}
On a side note, you should totally rethink your coding style/conventions. I'm fully aware it works, but having id_contacto_x_agendamiento as a primary id or a class name like Contacto_x_Agendamiento isn't best practice.
Having a mix of English and Spanish in classes/properties/variables could also be avoided, to improve other people's readability.

Why eloquent doesn't return error on diffrent primarykey?

I was working on an old database which primarykey is 'Id'. Eloquent set up the primary key to default 'id', so it is little change, but still can be confusing. Of course I didnt notice that, and I wanted to save updated models to database. There was no error, and $model->save() return was good but database didn't update. Furthermore I have other functions that get models from the database, and they work as they should without overriding $primarykey.
So here is my question: Why isn't eloquent returning any warnings or errors ? Of course I found in the documentation that I should override $primarykey in the model, and then everything worked perfectly.
I was using MySql 10.1.16-MariaDB.
Here is Laravel controller
public function update(Request $request, Order $order)
{
$order->fill($request->get('data'));
$order->save();
$order->products;
return $order;
}
Vue.js function
editOrder () {
this.fullscreenLoading = true
axios.put('/web/' + this.url + '/' + this.rowId, {'data': this.row})
.then(({data}) => {
this.row = data;
this.fullscreenLoading = false
});
},
Laravel Model was standard, of course my model is now properly updated, when i got this problem there was no $primarykey, I didnt mention $fillable and relationship to products but in my project they are defined and working.
class Order extends Model
{
use LogsActivity;
protected $table = 'orders';
protected $primaryKey = 'Id';
protected $fillable = []
}
If you execute the query with get(), create() or similar method, it will work as before because Eloquent doesn't use PK in this case. But some methods like find() will not work for you until you setup $primaryKey property in the model.
You didn't get an error because there was no error.
When you ran $order->save(), the query generated would have been something like:
update `orders` set `field1` = ?, `fieldN` = ?, `updated_at` = ? where `id` is null
This is a perfectly valid SQL statement, and when it runs, it would produce no errors. However, it will also not update any records (unless you do have a record where the id is null).
The reason why the update query is using null is because your Order model does not have an id attribute, it has an Id attribute, and PHP array keys are case-sensitive. So, when Laravel attempts to get the value for the id attribute, it returns null, and uses that in the query.

Save issue in 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.

custom `id` name using `insertGetId` fluent method of Laravel

According to Laravel's documentation:Inserts
Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".
So, is there a workaround for a custom id name while using inserGetId. i.e.
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
You can use the Eloquent method Model::create() to return the object inserted, and obtain the object id, whatever his name is.
Try this:
$user = User::create(['email'=>'john#ecample.com','votes'=>0]);
$id = $user->custom_id;
This works if your User model is like:
class User extends Eloquent {
//This custom_id column needs to be of type serial in your table
protected $primaryKey = 'custom_id';
protected $fillable = ['email','votes'];
//...more code ...
}
I hope this works for you

Laravel 4 : Can't add new element in a database

I am new in Laravel 4 framework, I am working on library management project. I get all the data from my DB but I can't add a new book to my database.
I've created a form to add new books to my database. I get the Input::get('element') value from my store() method but the create Methode doesn't work . here's my code to save a new book :
Livre::create(array('titre' => Input::get('titre'),
'resume'=> Input::get('resume') ));
and here's my Model :
class Livre extends Eloquent {
protected $table = 'livre';
}
You need to create a new Model instance by calling:
$livre = new Livre;
Then add your 'fields':
$livre->titre = Input::get('titre');
$livre->resume = Input::get('resume');
Then save your new book by calling the save() or push() method:
$livre->save();
Or if you'd like to save a model with its relationships, use the push() method:
$livre->push();
Seems that when you say that create method doesn't work you mean that the record in your DB is created, but it has empty values. This happens when you dont't specify the fields enabled for massive assignment.
By default , the Eloquent model has the guarded attribute set to a wildcard blocking of mass assignment. To use the code that you showed us, modify your model :
class Livre extends Eloquent {
protected $table = 'livre';
protected $fillable = array(
'titre',
'resume'
);
}
You can read more here : Mass Assignment

Resources