dimanche 29 avril 2018

Why my detach() and delete() don't work?

I'm working with Laravel 5 and I'm trying to delete some data from database

HTML

<form method="post" action="">
    
    
    <button type="submit" class="btn btn-danger btn-sm" dusk="btn-confirmDeletePub">Yes, Delete</button>
</form>

web.php

Route::resource('publications','PublicationController');

Publication.php (Model)

public function users()
{
    return $this->belongsToMany('App\User', 'user_publication');
}

public function topics()
{
    return $this->belongsToMany('App\Topic', 'topic_publication');
}

public function authors()
{
    return $this->belongsToMany('App\Author', 'author_publication');
}

public function details()
{
        /*
        Since we must join the publications table with one of the
        journals/conference/editorship table (based on type column' value)
        to retrieve publication'details,  we "aggregate" the 3 alternatives in this method.

        this method is useful for retrieving from db, 
        for insertions, the 3 methods above ( journal(),conference(),editorship())
        should be used
        */
        switch ($this->type) {
            case 'journal':
                return $this->hasOne('App\Journal');
                break;

            case 'conference':
                return $this->hasOne('App\Conference');
                break;

            case 'editorship':
                return $this->hasOne('App\Editorship');
                break;

        }
 }

PublicationController.php

public function destroy($id)
{
    $publication = Publication::find($id);
    $publication->users()->detach($publication->id);
    $publication->topics()->detach($publication->id);
    $publication->authors()->detach($publication->id);
    //dd($publication);
    $publication->details()->delete();

    //$publication->delete();

    //Redirect('/users')->with('success', 'Publication deleted correctly.');

    return redirect('/users')->with('success', 'Publication deleted correctly.');

}

When I click on the Yes, Delete button in the HTML form, it calls the destroy method in PublicationController to delete the Publication with the specific id. I tried to comment all the code and leave only the return redirect to see if the method is called, and it works. After that, I removed the comments to the detach() functions, but inexplicably in the database they don't produce any results. Finally, I removed the comment at the $publication->details()->delete(); and my application crashes.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire