Laravel cannot set id on eloquent creating event - php

I'm trying to give my modal a custom id (no auto increment). So I've overwrite the boot method of my modal. The creating event is used like this:
public static function boot()
{
static::creating(function ($modal) {
$modal->id = $myID;
return true;
});
}
Now when I try to revert the id after saving an entry the id of the new entry is alwas 0.
$modal = new Modal;
$modal->myValue = $myValue;
$modal->save();
dd($modal->id) // This will returns always 0
The strange thing is that the record is successful written to the database with the right id.
What is wrong with my code?
Edit:
It's not returning null. It's returning 0

You need to disable auto increment with setting property $incrementing to false in your model.
public $incrementing = false

Related

Primary Key is different from the default id that laravel searches for

I have added a custom primary key within the table and now the Laravel is not even finding the result at all. giving error that the page could not be found.
NotFoundHttpException
No query results for model [App\usersinformation].
Controller --------------------
public function show(usersinformation $usersinformation)
{
//
// $users = $user = usersinformation::where('user-id','=',$usersinformation) -> first();
return view('usersinformation.show');
}
Model -------------------
class usersinformation extends Model
{
//
public $table = "usersinformation";
public $incrementing = false;
protected $fillable = [
'fname','lname', 'user-picture', 'phone-number', 'user-id', 'place-id'
];
protected $primaryKey = 'user-info-id';
public function users(){
$this -> belongsTo('App\users');
}
route ---- web.php
Route::post('/show','App\Http\Controllers\usersinformationController#show');
Still facing the same issue, if I comment the primary key, it will give error that the id field is not found within the table when I add the custom primary key in the model, it will give error page not found.
You're typehinting usersinformation $usersinformation, so it's trying to find the record for the ID you're passing in. In the next line, you're trying to pass the id into the user-id, so I'm guessing you're actually passing in the user-id to the route, and not the id of the user information row. If that is the case, then you need to change the typehinting so it won't try to find the record before it enters the function.
public function show($user_id)
{
$user_information = usersinformation::where('user-id','=',$user_id) -> first();
return view('usersinformation.show', ['userinformation' => $user_information]);
}
Your primaryKey line is fine and should work, but know that dashes in table and column names are strongly discouraged because it leads to all sorts of confusion. Underscores are much better. See this link for more information.

Laravel populate non null fields while creating

Laravel populate non-null fields while creating without a default value.
In users migration I added $table->string('username').
What is the best way to auto-populate this?
Using boot/booted method within User model:
protected static function booted () {
if (auth()->user()) {
self::creating(function ($model) {
$model->username = self::generateUsername(self::name);
});
}
}
This doesn't work because the username column is not null and has no default value. I could add nullable or default value as something but that seems like a wrong thing to do.
Ofc, I can add on create as well
User::create($request->validated() + ['username'=>User::generateUsername($request->name)])
But I want to leave it to auto-populate.
Now I am not sure is creating method run on the start of creating or end..
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
$this->attributes['username'] = $this->generateUsername($value);
}
This solved it :D

Update Boolean in User-Model Laravel

I have a problem updating a field in my User Model.
I have a field for activating a public_profile defined as boolean:
...
$table->boolean('public_profile')->default(false);
...
in the Model itself i define.
protected $fillable = [..., 'public_profile', ...];
Now i try to update the field via axios depending on the status of an checkbox.
$('#change_public_profile').change(function () {
message={
_token: $('meta[name="csrf-token"]').attr('content'),
public_profile: $('#change_public_profile').is(':checked')
}
axios.post('SOME URL', message).....
Now in my controller i read the request:
$public_profile = $request->input('public_profile');
And call the function:
Auth::user()->togglePublicProfile($public_profile);
In the User Model I have the function:
public function togglePublicProfile($toggleTo){
$user = $this;
$user->public_profile = $toggleTo;
return $user->save();
}
I also tried with boolval() as Mutator, but it never changed.
I do the same to chagne a string value, and there it works well.
Where is my mistake?
Since you have boolean (true/false) you dont need to get any input ($toggleTo) because you only have two states. Each time you call this option you can set the opposite value.
$this->public_profile = !$this->public_profile;
$this->save();

Save current user_id as default post owner field automatically in laravel eloquent models

Suppose I have a Post model by this Attributes :
post_id
title
description
owner //=> type same as user_id of User Model
created_at
updated_at
And now I want to fill out owner field with current (Authenticated) user ID on store action of PostConroller when using Create Model. (owner value not included in $dataArray and should automatically get user_id):
Post::create($dataArray)
Is there a way to do that?
In your model class, add save function override:
public function save(array $options = array())
{
$this->owner = auth()->id();
parent::save($options);
}
That's automatic. Just be carefull if you tend to use save in any other scenario so you don't overwrite owner.
I'm not sure what do you mean by automatically, but you can add user_id to an array:
$dataArray['owner'] = $user_id;
Post::create($dataArray);
But usually you're using collections when creating new model, so:
$dataCollection->put('owner', $user_id);
Post::create($dataCollection);
will add user_id to collection.
Also, do not forget to add owner to $fillable array.
public function save(array $options = []) {
if (!isset($this->user_id) || !(intval($this->user_id)>0) ) {
$this->user_id = auth()->id();
}
return parent::save($options);
}
If your user->id's are number
Remember the return, else save is always false
I#m stuck on this too.
Automatic means that you can provide ALL other data, but when a create is called, the model just knows to add user to equal Auth:id()
like this? (but this isn't working for me
protected static function booting(): void
{
static::creating(function ($product) {
$product->user_id = Auth::id();
});
}

Laravel4 Model primary key value is lost after insert

<?php
// Model
class ProfileDelivery extends \Eloquent {
protected $table = 'profile_delivery';
protected $guarded = array();
public $timestamps = FALSE;
}
// Somewhere
$deliveryGuy->id = 1;
print $deliveryGuy->id; // Prints 1
if (!$deliveryGuy->save()) {
throw new \Exception('Cant save .');
}
print $deliveryGuy->id; // Prints 0
Can anyone explain me why the ID value is lost?
Not sure if you solved this for your situation but in Laravel 5.1 this just happened to me - the primary key of one table is the same as the primary key to another table because there is a 0 or 1 - to - 1 relationship between them.
What is happening is that Eloquent is assigning the primary key to the last insert id of the insert, but because the primary key is not an auto increment value, it is assigning it to zero. It is stored in the database correctly, but the model after the save is not useful if you need to use that key. The solution is to override the insertAndSetId function for the model that has the foreign primary key to prevent its setting of the primary key attribute. Of course, you don't want to do this for any models that do have an auto-incrementing key, just models that you are assigning the primary key manually. It's also not necessary if you don't need to use the model immediately after creating it because as I said above the database has the correct info in it.
protected function insertAndSetId(Builder $query, $attributes)
{
$id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
// $this->setAttribute($keyName, $id);
}
This is because your id column in the database probably does not have autoincrement set.
I tried this with a test model without autoincrement and it returns 0, but when I changed the id column to autoincrement it returned the id correctly.
Check this function in laravel/Framework/Src/Illuminate/Database/Eloquent/Model.php
It says it will insert and set id if it has autoincrement.
protected function performInsert($query)
{
if ($this->fireModelEvent('creating') === false) return false;
// First we'll need to create a fresh query instance and touch the creation and
// update timestamps on this model, which are maintained by us for developer
// convenience. After, we will just continue saving these model instances.
if ($this->timestamps)
{
$this->updateTimestamps();
}
// If the model has an incrementing key, we can use the "insertGetId" method on
// the query builder, which will give us back the final inserted ID for this
// table from the database. Not all tables have to be incrementing though.
$attributes = $this->attributes;
if ($this->incrementing)
{
$this->insertAndSetId($query, $attributes);
}
// If the table is not incrementing we'll simply insert this attributes as they
// are, as this attributes arrays must contain an "id" column already placed
// there by the developer as the manually determined key for these models.
else
{
$query->insert($attributes);
}
// We will go ahead and set the exists property to true, so that it is set when
// the created event is fired, just in case the developer tries to update it
// during the event. This will allow them to do so and run an update here.
$this->exists = true;
$this->fireModelEvent('created', false);
return true;
}
For me, I had to set protect $primaryKey to the column name of the primary key in the model to solve the issue. (skill_id was the column name so in the Skill model I set protected $primaryKey = 'skill_id', default is 'id'.)

Categories