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();
}
}
/**
* 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);
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With