Ezra Ezra - 3 months ago 15
PHP Question

can't delete data eloquent in laravel 5.2

i want to delete eloquent data from 2 tables. Table dosen and users.

eloquent : id and user_id

1.users(id, name, username, email, password, admin, remember_token, updated_at, created_at)

2.dosen (iddosen, user_id, namadosen, nipy, alamatdosen, notelpdosen, etc)

this is my method :

public function destroy($id)
{
$dosenUpdate = Request::all();
$user = User::find($id);
$user->dosen()->delete($dosenUpdate);
return redirect('admin/dosen')->with('message', 'Data berhasil dihapus!');
}


when i use that method, data from table dosen is deleted. but in table users there's still data . if i changed my method to :

public function destroy($id)
{
$dosenUpdate = Request::all();
$user = User::find($id)->delete();
$user->dosen()->delete($dosenUpdate);
return redirect('admin/dosen')->with('message', 'Data berhasil dihapus!');
}


i got error :

Call to a member function dosen() on boolean


what is the right code?

Answer

In your destroy() method you are storing the Boolean value in $user instead of User Model, as you are deleting the model in following line

$user = User::find($id)->delete();

This line is deleting the user model and returning the status of query i.e. if it is successful or not. Hence, $user is storing the status of delete() method and not the user model

change your destroy() method to below:

public function destroy($id)
{       
$dosenUpdate = Request::all();
$user = User::find($id);
$user->dosen()->delete($dosenUpdate);
$user->delete();
    return redirect('admin/dosen')->with('message', 'Data berhasil dihapus!');
}
Comments