Get newly created id inside laravel 'created' event - laravel

I am using laravel created event. I want to use newly created id in another table. But when i print created object, i don't get the id property. How can i get newly created id in created event.
This is my code.
public static function booted()
{
static::created(function ($agentTask)
{
echo $agentTask->id;
print_r($agentTask);
});
}
echo statement printing null. and when i print $agentTask object, i don't find id anywhere.

it should be boot not booted
public static function boot()
booted is used to perform any actions required after the model boots.
while boot is used to bootstrap the model and its traits.
Laravel API DOC: booted() boot()

Related

Updating a model property by POST API, can run an event?

The clear description is, an API with the post method updates a value of a model property. how I can set up a listener in Laravel that after every change by API, run an event for example send email or sms?
If you were wanting to create an event when any update happened you could easily just do this via the boot.
class SomeModel extends Model
{
public static function boot()
{
static::updated(function ($model) {
// send your email/sms
});
parent::boot();
}
}
However this would trigger when ever the model is updated, Since you only want this when you are updating via the API you would want to create a custom event and trigger it via dispatch in your api route/controller.
https://laravel.com/docs/8.x/events#dispatching-events

Laravel deleting cache working in controller but not in model closure

I'd like to delete a specific model from the cache using its id. This works as expected in the controller, but not using the model closure.
What I have in App\Models\Post:
use Illuminate\Support\Facades\Cache;
protected static function booted()
{
static::updated(function ($post) {
Cache::forget('post:'.$post->id);
});
}
If I do Cache::forget('post:'.$post->id); in the controller it works.
Something I'm missing?
Make sure that you are actually changing a value on your model, because the updated event only fires when the model was dirty, as you can see here.
The saved event however will fire whenever you call the save() method, as you can see here:
protected static function booted()
{
static::saved(function ($post) {
Cache::forget('post:'.$post->id);
});
}
From the docs:
The retrieved event will fire when an existing model is retrieved from
the database. When a new model is saved for the first time, the
creating and created events will fire. If a model already existed in
the database and the save method is called, the updating / updated
events will fire. However, in both cases, the saving / saved events
will fire.

Laravel Eloquent model events on created user

I'm trying to automatically create a profile for a user when a user is created.
I'm using the created event and overriding the boot() method. But I when call the create() method on user->profile->create(), it says create was called on null. I checked and profile is null in this.
Here's the code:
static::created(function ($user) {
// it returns profile as null, thus create() can't be used on null.
$user->profile->create(['title' => $user->username,]);
});
Can anyone help me understand this? It's working in my tutor's code, and he is using Laravel 5.8 but I have version 7.1.
$user->profile returns the related model if any exists. You have to do $user->profile() which returns a query builder to query the relation. Try to do it like so:
$user->profile()->create(['title' => $user->username,]);

Laravel Nova Observe not connecting to tenant database

I have a multi tenant App. My system database I have models- User, Billing, FrontEnd ... and using policies I'm able to show, hide and prevent viewing and actions by tenant.
Each tenant has a database with models- Member, Event, Item ...
I set each model database based on the Auth::user()->dbname in the _construct method. This allows me to set my dbname to a clients database for tech support.
class Item extendsw Model {
public function __construct() {
parent::__construct();
if(Auth::user()->dbname) {
Config::set('database.connections.tenant.database', auth()->user()->dbname);
$this->connection = 'tenant';
}
}
This all works as planned until I add and Observer for a client model e.g. Member
I now get an error on any Observer call.
Trying to get property on non object Auth::user()->dbname.
Where should I be registering the Observer? I tried AppServiceProvider and NovaServiceProvider.
I think that happens because the observer instantiates your User model before the request cycle has started and that means that your User instance does not exist yet neither has been bound in the Auth facade.
Thus, Auth::user() returns null and you are trying to get a property from it.
A way to solve the issue may be to check if the user instance exists or not:
public function __construct() {
parent::__construct();
if (optional(Auth::user())->dbname !== null) {
Config::set('database.connections.tenant.database', auth()->user()->dbname);
$this->connection = 'tenant';
}
}
The optional helper return the value of the accessed property (dbname in your case) if and only if the argument is not null, otherwise the whole call will return a null value instead throwing an exception.
If that is not the case, maybe update the question with the error stacktrack and the code/action that triggers the error

How to hook into the delete event for a resource in laravel nova?

I have one query, I want to delete the image from the server when particular resource get deleted from Nova.
can anyone suggest me is there any way to override delete method for the resource.
EDIT: How to hook into the delete event for a resource in laravel nova?
Note: I know we can do using observer. but I am looking for another
way.
In order to hook into laravel nova's delete resource event, you don't have a builtin way. But the parent model's have a delete method, you can override it and do extra work there
//app/ParentModel.php
public function delete() {
/* add your extra logic for deleted model */
parent::delete();
}
you can use boot in your model like this:
public static function boot()
{
parent::boot();
self::deleted(function ($model) {
parent::remove($model, self::$index);
});
}
I used Observers and deleted function Nova Resource Events and works fine

Resources