dimanche 2 septembre 2018

Laravel - can't get model after deleting related model records

I have a function postShippingmethods in which I delete, update or create new shipping methods depending what the user specified in the form. It works like it should , except that if any methods are deleted, I get empty result when trying to retrieve the user model with the updated methods.

To delete methods, I first get the user:

$user = \App\User::where('id',$id)->with(['shipping_profiles' => function($query) {
                    $query->where('default', 1);
                }, 'shipping_profiles.methods' ])->first();

I compare the stored methods to the ones in the request; if any are missing , they should be deleted.

This code does the deletion:

 foreach($non_included_ids as $id){
                    $method = \App\ShippingMethod::find($id);
                    $method->suppliers()->detach();
                    $method->delete();
                } 

Then I get the user once again, to get the updated data:

$user = \App\User::where('id',$id)->with(['shipping_profiles' => function($query) {
                    $query->where('default', 1);
                }, 'shipping_profiles.methods' ])->first();

^^ this works well if nothing was deleted, but for some reason if something was deleted, the above code will return nothing. And when I try to use the $user to retrieve data I of course get "Trying to get property of non object".

So can anyone explain why this happen and what I should do to get the user with the updated data?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire