I have two tables in my database - vnames and vtypes
vtypes have a name field and an id field, vnames have an id field, a name field and a vtypes_id field, which is the field associated with the foreign key. It is associated with the id field in views.
I have Vname and Vtype models -
Vname
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Vname extends Model { public function vtype() { return $this->belongsTo('App\Vtype'); } }
VType
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Vtype extends Model { public function vname() { return $this->hasMany('App\Vtype'); } }
When I delete any column in the vtype table, I want to delete all the vname columns associated with it. I found a solution like this -
public function vtypeDestroy($id) { $vtype = Vtype::find($id); $vtype->vname()->detach(); $vtype->delete(); Session::flash('success', 'The vtype was successfully deleted'); return redirect('/vtypes'); }
but when I run this function, I get this error: Call to undefined method Illuminate\Database\Query\Builder::detach()
How can i fix this?
And when I want to get the vtype name from vname, I cannot do this. I tried like this
@foreach ($vnames as $vname) {{ $vname->vtype()->name }} @endforeach
in view
But I have such an error - Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Please tell me how to fix these two problems that I am facing right now.
source share