mercredi 31 octobre 2018

Eloquent many-to-many get data

So guys, i'm starting studying laravel, but currently I'm stuck in a problem which I cannot find any solution... I've found some related solutions but after tryed none solved my problem, so it'is:

I'm in step of creating a blog, so I have posts, tags, and categories. A post belongs to just one category, and categories can belongs to many posts, from here... OK! Now, posts belongs to many tags, as tags belong to many posts... Problem!

I have my pivot table, and everything is running ok, the real problem is when I need to retrieve data from this pivot table, I cannot figure out how it should work.

What I'm trying to do is basically the user can only delete a tag if there's no posts associated to it.

Post Model

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

Tag Model

public function posts()
{
    $this->belongsToMany('App\Post');
}

Tag Controller (Delete Method)

public function delete($id)
{
    // Get tag by ID
    $tag = Tag::find($id);
    $tag_name = $tag->tag;

    /** Try to check data */
    if($tag->posts->count() > 0) {
        Session::flash('error', 'There is some associated posts to "' . $tag_name . '", delete them before.');
    } else {
        Session::flash('success', 'Tag "' . $tag_name . '" was deleted successfully.');
        //$tag->delete();
    }

    return redirect()->back();
}

I've tried

$tag->posts()->get()
$tag->posts->get()
Tag::find(1)->posts->get()
Tag::where('id', [1])->get()

Some other combinations, every single one return an Logic Exception or a Fatal error...

App\Tag::posts must return a relationship instance

View Button (Passing the ID)

<a href="" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i> Delete</a>

Route in web.php

Route::get('/tags/delete/{id}', 'TagsController@delete')->name('tags.delete');

I'm struggling in retrieve data from many-to-many data for a long time, it starts to getting very stressful.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire