Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LARAVEL : Destroy and detach method

I'm trying to delete a Poll with this function where I need to detach relations :

public function destroy($id)
{
    $poll = Poll::findOrFail($id);
    $poll->answers()->detach();
    $poll->poll_user()->detach();
    $poll->delete();
}

But I'm getting this error message, I don't know why :

Call to undefined method Illuminate\Database\Query\Builder::detach()

Here is the Poll model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Poll extends Model
{

    /**
     * La table utilisée par le modèle
     *
     * @var string
     */
    protected $table = 'polls';

    /**
     * On utilise les dates de mise à jour
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * Attributs autorisés en ensignement de masse.
     *
     * @var array
     */
    protected $fillable = ['question'];

    /**
     * Relation de type 1:n
     *
     * @return Illuminate\Database\Eloquent\Relations
     */
    public function answers()
    {
        return $this->hasMany('App\Models\Answer');
    }

    /**
     * Relation de type n:n
     *
     * @return Illuminate\Database\Eloquent\Relations
     */
    public function users()
    {
        return $this->belongsToMany('App\Models\User')->withTimestamps();
    }
 }
like image 904
Patrick Rey Avatar asked Dec 28 '16 10:12

Patrick Rey


2 Answers

/**
 * Removing an entity
 *
 * @param  integer $id
 * @return void
 */
public function destroy($id)
{
    $this->getById($id)->users()->detach();
    $this->getById($id)->answers()->delete();
    $this->getById($id)->delete();
}

/**
 * Getting an entity by id
 *
 * @param  integer $id
 * @return void
 */
public function getById($id)
{
    return Poll::find($id);
}
like image 65
Houssine Sghaire Avatar answered Oct 02 '22 14:10

Houssine Sghaire


Well I don't know if it's correct or not but I've done the following and it works perfectly :

public function destroy($id)
{
    $poll = Poll::findOrFail($id);
    $poll->answers()->delete();

    $poll->users()->detach();
    $poll->delete();
}
like image 36
Patrick Rey Avatar answered Oct 02 '22 16:10

Patrick Rey