Laravel - delete whole collection

If you have your Models linked, you can.

Class Exercise.php:

/**
 * Exercise belongs to exactly one lecture
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */

public function lecture()
{
    return $this->belongsTo('\App\Lecture');
}

and Class Lecture.php:

/**
 * Gets all the exercises asociated to this lecture
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */

public function exercises()
{
    return $this->hasMany('\App\Exercise');
}

Then you can in your controller simply do:

public function delete($id, DeleteLectureRequest $request)
{
        $lecture = Lecture::findOrFail($id);
        $lecture->exercises()->delete();      // easy
}

(Imagine that your Article == my Lecture, and your Media == my Exerises)

Of course, at first you have to set properly foreign keys in your DB and link your Models that way.


You just can't delete from database without making a query.

You will have to make new request like this:

Media::where('article_id', $article->id)->delete();

It's just one simple query, so there shouldn't be any performance penalty.

If we are talking about collection with 100's of items, you can optimize the query like this:

Media::whereIn('id', $images->pluck('id'))->delete(); 

Tags:

Php

Laravel