简体   繁体   中英

Laravel Eloquent - Find all records from a given month

I have the following route.

Route::get('/blog/{search}/{slug}', array(
    'as' => 'public-blog-filter',
    function ($search, $slug) {

      if($search == 'search' ) {
        $search = 'title';
      } elseif($search == 'category') {
        $search = 'blog_category_id';
      } elseif($search == 'archives') {
        $search = 'published_at';
      }

      //$blogArticleId = trimIdFromSlug($slug);
      $blogPosts = Bugz\BlogArticle::where($search, 'LIKE', $slug)->get();

      dd($blogPosts);

      //show the page:
      $viewData = array(
          'metaTitle'         => 'Blog | ' . config('app.name'),
          'metaSectionJs'     => 'public-blog-single',
          'metaSectionParent' => 'public-blog-single',
          'metaSectionUrl'    => '/blog/{slug}'
      );

      return view('public.blog', compact('viewData', 'blogPosts'));

    }
));

In my blog people can either filter blog posts by Archives, Category or Search.

Deepening on what they searched for, I change the the $search variable to a column in the database table. The slug then is the string which I'm searching for.

If I click on "October 2015" then the URL is: /blog/archives/2015-10

In the database the records are stored as 2015-10-31 11:32:00

However the query is not returning anything even though the published_at column contains records that contain the string I'm looking for.

It's just a minor thing, you need to add the wildcard to your query:

  $blogPosts = Bugz\BlogArticle::where($search, 'LIKE', $slug.'%')->get();

So this will look for dates starting with 2015-10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM