samedi 5 décembre 2015

How to display articles with certain categories that match form input - Laravel

I cannot limit my search/display my results based on their categories.

I have a many to many relationship. An article has many categories and a category has many articles. A user enters an address into a form and chooses 1-3 categories. I then want to match these user specified categories with articles from my db that have these categories and only display these particular articles.

I've been looking at many SO questions like THIS ONE and can't seem to get things to work. My main error is that I get an undefined property of $categories.

Before I added the category stuff it was working and I could display a list of articles that were within a certain distance. I'm using Laravel 5.1.

Database tables: 'articles' (id, title, etc...) 'categories' (id, name) 'article_category' (article_id, category_id)

Here is my code:

Article Model:

    public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }

public function getCategoryListAttribute()
    {
        return $this->categories->lists('id')->all();
    }

Category model:

    public function articles()
{
    return $this->belongsToMany('App\Article')->withTimestamps();
}

Articles Controller

public function index(Request $request)
    {

    $lat = $request->get('lat');
    $lng = $request->get('lng');
<--! THIS GETS THE USER DEFINED CATEGORY CHOICES -->
    $categoryChoice = $request->get('categoryList');
    $distance = 1;

    $query = Article::getByDistance($lat, $lng, $distance);

        if(empty($query)) {
        return redirect()->action('HomeController@index');
        }

        $ids = [];

        //Extracts the alticle/store id's
        foreach($query as $q)
        {
          array_push($ids, $q->id);
        }

<--! Get the listings that match the returned ids -->
        $results = DB::table('articles')
        ->whereIn( 'id', $ids)
        ->orderBy('title', 'DESC')
        ->paginate(6);   

       $articles = $results; 

<--! THIS IS TO GET CATEGORY IDS OF NEARBY STORES - NOT WORKING ->
        $categoryMatches = [];

        foreach ($articles->categories as $category){

            array_push($categoryMatches, $category->pivot->category_id);

        }

<--! THIS WILL IDENTIFY WHETHER THE CATEGORIES OF NEARBY STORES MATCH THE CATEGORIES CHOSEN IN THE FORM - NOT WORKING -->
        $articles = $articles->whereIn($categoryMatches, $categoryChoice);

        return view('articles.index', compact('categories', 'days'))->withArticles($articles);

    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire