samedi 26 septembre 2015

Selecting and ordering data from a query using Laravel Eloquent

I am trying to use Laravel and eloquent to return results based on the following query.

$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->orderBy('created_at', 'desc')
->paginate(5);

Ok, so that is fine, it return exactly what it should, all the blog posts with associated relations to other tables.

What I now want to do is return only the $blogPosts where a tag is clicked by the user. So let's say there is a tag "PHP", so I pass in that value as $tag to the method. I then have something like this.

public function tag_search($tag)
{

    $blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
        ->where('tags', $tag)
        ->orderBy('created_at', 'desc')
        ->paginate(5);

    $categories = BlogCategories::with('blog_posts')->get();

    $data = array('blogPosts' => $blogPosts, 'categories' => $categories,
                  );
    return view('blog.index')->with($data);
}

Now my issue is actually relatively simple I guess, if the where clause was a column in the BlogPosts table it would work, I know this because I tried that.

However the above won't work as is, I can only use;

->where('x', y)

Where x is a field in the BlogPosts table. I want to return a set of values where the submitted $tag is the same as one associated to the tags attached to the blog posts.

Make sense? I think I am over thinking it the point I am just not thinking now :)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire