Laravel 5.1 Event deleting and delete not fire - php

I Works with Laravel 5.1 and works with events creating, updating, deleting. creating and updating works fine, but deleting method not fire. I have tests in Model, creating an Observer class and put into EventServiceProvider without any solution.
My code:
public static function boot()
{
parent::boot();
static::deleting(function($user)
{
if(count($user->getImages()) >0){
return false;
}else{
return true;
}
});
}
My code delete:
User::where('id','=',$id)->delete();
Any suggestion? Thank for all in advance

Try to use User::where('id','=',$id)->first()->delete(); It must be work, I have the same bug in my project.
For multiple rows:
User::where('id', $id)->get()->each(function($row){
$row->delete();
});

the next option if you shoot the events deleted, deleting
User::destroy(id);
or
User::destroy([id1, id2, id3]);

Related

Model Observer Not updating if i'm getting Data From FormRequest

i'm using UserObserver and it's working only if i updated My in this way
User::find(1)->update(['name'=> 'vich']);
but when i try to do
public function update_user_profile(UpdateProfileRequest $request)
{
$user = User::find(1)->update($request->validated());
}
then the observer will not fire update event but the tow ways are updating without any errors
My Observer
public function updating(User $user)
{
dd('99');
}
I think the updated values are not 'dirty' meaning they have the same value as in the database and thus not firing any query. Not sure though, but you can try using different values will it fire then?

Diffrence between find and where when fire update event in laravel

When i tried to use Eloquent event (update) it works fine to me , but i noticed that event doesn't fired when i wrote this query
Samples::where('id', $id)->update($inputs);
but it works when i wrote this
Samples::find($id)->update($inputs);
and this is my update event
public static function boot()
{
static::updating(function ($model) {
dd('it works !');
parent::boot();
}
Your first code will directly generate an UPDATE query and send it to the database. It will never load any model.
The second code will first execute a SELECT query to fill a model and then it will do an UPDATE query using the received data.
This is why the first query will never fire your update event.

Laravel 5.2 Eloquent hasOne relationship doesn't work

I have relationship in my chat model
public function user() {
return $this->hasOne(User::class,'id','writers_id');
}
And want to use it in my controller. I tryed many ways, but no one worked. Just giving last try example (result - blank page).
print_r($chat = Chat::where('id', 1)->first()->user);
Can anyone help me? Thanks! I don't really understand that Eloquent, used simple DB query maker before, however someone said that I should do every database stuff in model. Is it correct? Sorry about my poor English!
First as mentioned by #Vohuman
return $this->hasOne('App\User', 'id', 'writers_id');
And when using it:
Chat::where('id', 1)->first()->user()->first()->attribute
Look here: https://laravel.com/docs/master/eloquent-relationships#one-to-one
In App\Chat.php:
public function writer()
{
return $this->hasOne('App\User','id','writers_id');
}
to define the relation. Then in whatever controller:
At top:
use App\User;
and inside the method:
$writer = User::find($user_id)->writer;
to debug it add one line in front of the above line.
dd($user_id,User::find($user_id),$writer);

Laravel force delete event on relations

I'm developing a Laravel web app using Laravel 5.2. My question is very simple... How do I listen to a forceDelete event in order to forceDelete model relations?
I've been looking around the web and S.O. for a few but all the questions/answers I've found where releted to the delete method, and also in the API documentation I haven't found very much...
In my case I have a Registry model and a RegistryDetail model
Registry table
|id|name|surname|....
RegistryDetail table
|id|id_registry|....
I've created for both this boot function:
protected static function boot()
{
parent::boot();
static::deleted(function($registry) {
// Delete registry_detail
$registry->registryDetail->delete();
});
static::restored(function($registry) {
// Restore registry_detail
$registry->registrydetail()->withTrashed()->restore();
});
}
Since both models have SoftDeletes the static::deleted function is called only when the delete() method is called. if I call a forceDelete() method the related model won't be deleted from the database.
If you need more informations let me know.
Thanks in advance
The deleted event should still fire when calling forceDelete(). Inside the deleted() event method, you can check the the forceDeleting protected property via isForceDeleting() to see if you're in a regular delete or a forced delete.
static::deleted(function($registry) {
// Delete registry_detail
if ($registry->isForceDeleting()) {
$registry->registryDetail->forceDelete();
} else {
$registry->registryDetail->delete();
}
});

count() returning soft deleted items in laravel

I have a model Comments that uses soft deleting: it has a one-to-many relationship with my Post model.
My site will have a native mobile app associated with it and I need to send a count of the comments to it when I send the information about a post and for some reason it is returning the count WITH the soft deleted items.
I've got the Post array working and sending the comment count using
protected $appends = array('score','commentcount', 'ups', 'downs');
and
public function getCommentcountAttribute()
{
return DB::table('comments')
->where('post_id',$this->id)
->where('deleted_at','=',NULL)
->count();
}
in my post model. I've also tried
public function getCommentcountAttribute()
{
return $this->comments()->count();
}
and
public function getCommentcountAttribute()
{
return $this->comments()->whereNull('deleted_at')->count();
// also: return $this->comments()->where('deleted_at',NULL)->count();
}
also when defining the relationship I've tried adding ->whereNUll('deleted_at') to both the ->hasMany('Comment') and the ->belongsTo('Post') with no luck.
I've checked the database and ran the SQL I'm expecting Fluent and Eloquent to be generating which is
SELECT * FROM `comments` WHERE post_id=31 and deleted_at=null
(31 being the post I'm using to test). Nothing is working. Let me know if you guys need to see anymore specific functions as I'd rather not post my entire models.
I was able to make it work with ->whereRaw('deleted_at = ?',array(NULL)). That seems pretty hacky to me though. I'd gladly accept a better answer.
You have to enable Soft Deleting in your model.
class Comment extends Eloquent {
protected $softDelete = true;
}
That's it.
And you don't need to include the following where clauses in your queries:
return DB::table('comments')
->where('post_id',$this->id)
//->where('deleted_at','=',NULL) // no needed, Laravel by default will include this condition
->count();
public function getCommentcountAttribute()
{
// remove ->whereNull('deleted_at')
return $this->comments()->count();
}
Change your code to:
return \App\Comments::count();
Soft delete works only on models, not queries:
class Comment extends Eloquent
{
protected $softDelete = true;
}
Whilst this is an old post the following should hopefully be helpful with others if they come across this.
For laravel V5 and above.
Add use SoftDeletes; to your model.
If you are trying to get the count that includes soft deletes use the following:
Model::withTrashed()->'yourquery'
If you do not want soft deleted records included then you can follow the normal convection.
Model::select()->get();

Categories