Dessauges Antoine
Dessauges Antoine

Reputation: 593

Laravel Eloquent : Has many delete, need to refresh

I have a strange problem, I have two table : Users and Companies, it's a has many relation :

 public function companies() {
    return $this->hasMany('App\Models\Company');
 }

I have delete on cascade in my companies table:

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

But now I have a strange problem, for some reason when an user want to create a company. I create it when he click the "add" button and return the edit form (because I need to have an id to attach pictures, etc.)

So if the user click on "create company" and quit the page, I have an empty row in my DB.

So in my user company index I do :

public function company_index() {
    $user = auth()->user();

    foreach ($user->companies as $company) {
      if($company->name == "")
         $company->delete();
    }
    $companies = $user->companies;

    return view('front.users.company')->withCompanies($companies);
}

My company with empty name is correctly delete in my DB but $companies = $user->companies; still get it. If i refresh it's work.

My question is : Why $companies = $user->companies; still get the companies I delete just before and how can I fix this ?

Thanks

Upvotes: 2

Views: 1663

Answers (1)

Maraboc
Maraboc

Reputation: 11093

To remove an item from a collection just use forget like this :

foreach ($user->companies as $key => $company) {
    if($company->name == ""){ 
        $user->companies->forget($key);
        $company->delete();
    }
}

Upvotes: 1

Related Questions