Khirad Zahra
Khirad Zahra

Reputation: 893

Delete all records from related tables using laravel eloquent

I have 3 tables.

Posts
Likes
Post_images.

// Model Relations.
Posts hasMany likes.
Likes belongs to Posts.
post hasMany PostImages
post_imags belongs to Posts.

Now when i delete a post record i want to delete its related records from likes table as well as from post_images table,Besides this images should also be removed from storage.

How can i accomplish this ? any guidance would be highly appreciated.

Upvotes: 1

Views: 4211

Answers (3)

saber tabatabaee yazdi
saber tabatabaee yazdi

Reputation: 4959

if you set table names with Models::table('abilities') in

    Schema::create(Models::table('abilities'), function (Blueprint $table) {
        $table->bigIncrements('id');
        // other fields
    }

you can use

    DB::table(Models::table('abilities'))->delete();

as documented here you can

/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
   Models::table('abilities');
}

Upvotes: 0

Gopakumar
Gopakumar

Reputation: 217

DB::table('users')->delete();

All users are deleted from 'user' Table

Upvotes: 2

Anar Bayramov
Anar Bayramov

Reputation: 11594

If I understand correctly your query should be like this. But you cannot remove images with eloquent relations. So you need to do something like

 $courses = \App\Course::all();
 foreach($courses $ $course){
      Storage::delete($course->image_column_name);
 }

 \App\Courses::with('sessions')->with('lessons')->delete();

I can give you better answer if you can share your models function, database schema and Storage information like where you store course images...

Upvotes: 2

Related Questions