Laravel schedule: creating new row in a table automatically - laravel

(Laravel framework) I'm trying to create new row automatically in a table using schedule inside the handle function but it's not adding the row to the table:
public function handle()
{
Reserved::create([
'book_id'=>1,
'user_id'=>1
]);
}
the schedule is working when I try other things like deleting a row or sending emails...
What can I do?

You probably haven't added the $fillable property to your Reserved model class. This prevents the create method from storing a new instance.
See Documentation: https://laravel.com/docs/9.x/eloquent#mass-assignment

Related

Updating laravel relationship data

When we inserting or updating the data via Eloquent relationship model, which is the best approach to use?
Example
$user->profile->update(['salary' => 5000]);
vs
$user->profile()->update(['salary' => 5000]);
I understand that
$user->profile() will return the relationship class such as Illuminate/Database/Eloquent/Relations/HasOne
$user->profile will return the actual UserProfile model class
I somehow remember I saw someone recommended to use $user->profile->update() instead of $user->profile()->update() but I couldn't find the article or reference link anymore
However, I found that if $user->profile is null, then it might caused an error such as
Call to a member function update() on null
So will it be easier to use relationship function update all the time?
$user->profile()->create()
$user->profile()->update()
$user->profile()->save()
$user->profile()->delete()
Is there any situation we should use the $user->profile->save() instead?
Or should one use it when it is in the multiple nested relationship?
$user->profile->bank()->create()
$user->profile()->bank()->create()
Update
reference link (for my own understanding)
https://github.com/laravel/framework/issues/13568
https://github.com/laravel/framework/issues/2536
Eloquent attach/detach/sync fires any event?
Conclusion
For now, will use code below in application, both will trigger events
if ($user->bank === null) {
$user->bank()->save(new UserBankAccount($input)); // trigger created event
// $user->bank()->create($input);// trigger created event
} else {
$user->bank->update($input); // trigger updated event
// $user->bank()->update($input); // will NOT trigger updated event
}
You can use forceFill()
Example:
$user->bank->forceFill($data)->save();

Laravel delete relationship and create new in one way?

Hi guys is it possible to do following code in one way?
$Project->deadline()->delete();
$Project->deadline()->create($deadline);
Project Model:
public function deadline()
{
return $this->hasOne('App\Models\UserProjectDeadline','projects_id','id');
}
Seems there's no methods for deleting and creating in one line of code, but Laravel offer functions updateOrCreate(array $attributes, array $values = []) that can be used for hasOne relationships.
$Project->deadline()->updateOrCreate($attributes, $deadline); // To update based on the attributes
Or if you want to change/update all the data without any specified attributes
$Project->deadline()->updateOrCreate([], $deadline); // To update all the data

Laravel Eloquent : Set custom formatted ID in Table

Is there any way where I can add custom formatted ID on create?
for example, there is a table 'Customers', in this table there are one primary key - 'ID (auto increment)' and one unique key 'customer_id'
Now, when I will create a new customer, the 'ID' is auto increment so it will automatically set in DB.
I want to set 'customer_id' like '2018-0001' at the time of create.
CurrentYear-000 INSERTED_ID
You could use the created model event for this. docs
Eloquent models fire several events, allowing you to hook into the
following points in a model's lifecycle: retrieved, creating, created,
updating, updated, saving, saved, deleting, deleted, restoring,
restored. Events allow you to easily execute code each time a specific
model class is saved or updated in the database. Each event receives
the instance of the model through its constructor.
After creating the customer you could generate the customer_id and save it:
Customer.php
use Carbon\Carbon;
class Customer extends Model
{
protected static function boot()
{
parent::boot();
static::created(function ($obj) {
$obj->customer_id = Carbon::now()->year.'-000'.$obj->id;
$obj->save();
});
}
}

Save vs update in laravel

What is the difference between save() and update() method in Laravel.
I have used save() method in case of update query but in few cases it acts as update and in few case it act as insert query function. Please let me know what exactly the difference between them.
These methods both allow you to save data to a database.
The save() method performs an INSERT when you create a new model which is currently is not present in your database table:
$flight = new Flight;
$flight->name = $request->name;
$flight->save(); // it will INSERT a new record
Also it can act like an UPDATE, when your model already exists in the database. So you can get the model, modify some properties and then save() it, actually performing db's UDPATE:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save(); //this will UPDATE the record with id=1
Theupdate() method allows you to update your models in more convenient way:
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]); // this will also update the record
So you don't even need to assign the retrieved model to any variable. Updated properties are passed as arguments.
Examples and more info in the Laravel's docs.
There is only one thing left unsaid in what #ginopane told about the difference and it's that if you use update method on a query builder result then laravel will ignore $fillable or $guard array of your model. This is especially important if you want to use Input::all() as an argument to update:
Post::where('id', $id)->update(Input::all());
So in this case if you use App\Flight::where('active', 1)->update(Input::all()); everything in your database will be updated even if you put it in $fillable. So make sure to use save and update methods on Eloquent instance and not Query builder one. The following code will be fine even if the user submit fields that you don't want to insert or update in your databse table:
// User model
protected $fillable = ['email', 'name'];
// controller
public function update($id)
{
$user = User::findOrFail($id);
// validate the input here, use Request to do the job or whatever you like
$user->update(Input::all());
return view('some_view')->with('notice', 'user updated');
}
Now, no matter what with the FORM being passed here, only name and email will be updated.
Hope this complete #ginopane answer
save() : you can look to it as the equivalent of the INSERT in sql, it will create a new model (and insert it in the database)
To create a new record in the database, create a new model instance, set attributes on the model, then call the save method
update() : you can look to it as the equivalent of the UPDATE in sql, it will create a new model (and insert it in the database)
The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value
code
$flight = App\Flight::find(1);
if (empty($flight)) {// you can do this condition to check if is empty
$flight= new Flight;//then create new object
}
$flight->name = 'New Flight Name';
$flight->save(); //this will UPDATE the record with id=1
for more detail doc

Laravel model events for attach/detach

I have 3 tables, products, taxonomies and product_taxonomy, as you can tell the 3rd table is a pivoting table. In taxonomies table, I hold a field called num_products which keeps track of the quantity of products that belongs to this taxonomy. Now how can I trigger a model event every time a product is attached to or detached from a taxonomy? I want to update that num_products value in the model event.
Laravel models have events that you can hook into. You have the following options:
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored
You'd code it like this:
User::creating(function($user)
{
if ( ! $user->isValid()) return false;
});
Docs: http://laravel.com/docs/4.2/eloquent#model-events
Or you could use Model Observers that are baked in. You have the following options:
creating
updating
saving
You would write a method on your model:
class UserObserver {
public function saving($model)
{
//
}
public function saved($model)
{
//
}
}
You can then register then register the observer:
User::observe(new UserObserver);
Docs: http://laravel.com/docs/4.2/eloquent#model-observers
Hope it helps.

Resources