Azima
Azima

Reputation: 4141

laravel database query not working as expected

I have a query as following:

$this->_data['news'] = PageContent::orderBy('created_at', 'desc')->where('category_id', 3)->where('status', 1)->first();

And in my index.blade.php file, data is displayed in such manner:

@if(count($news) > 0)
    <div class="post_list_content_unit col-sm-6">
        <div class="feature-image">
            <a href="{{URL::to('/')}}/about-us/news-event" class="entry-thumbnail">
                <img width="370" height="260"
                     src="{{URL::to('Uploads/pageContents/'.$news->image)}}"
                     alt="{{$news->title}}">
            </a>
        </div>
        <div class="post-list-content">
            <div class="post_list_inner_content_unit">
                <h3 class="post_list_title">
                    <a href="{{URL::to('/')}}/about-us/news-event"
                       rel="bookmark">{{$news->title}}</a>
                </h3>
                <div class="post_list_item_excerpt">
                    {!! str_limit($news->description, 300) !!}
                </div>
            </div>
        </div>
    </div>
@else
    <div></div>
@endif

But instead of showing records with only status=1, it is displaying data with status value 0 also.

Is there something wrong with the query?

Upvotes: 0

Views: 60

Answers (3)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try this :

$this->_data['news'] = PageContent::orderBy('created_at', 'desc')
            ->where(function($query) {
              $query->where('category_id', 3)
              $query->where('status', 1);
            })
            ->first();

Hope this work for you !!!

Upvotes: -1

M_Idrees
M_Idrees

Reputation: 2172

You can do it two ways by passing array in where clause:

$this->_data['news']  = DB::table('PageContent')
    ->orderBy('created_at', 'desc')
    ->where([
        ['category_id', '=', '3'],
        ['status', '=', '1'],
      ])->first();

Or by

$this->_data['news']  = PageContent::orderBy('created_at', 'desc')
    ->where([
        ['category_id', '=', '3'],
        ['status', '=', '1'],
      ])->first();

Upvotes: 0

ka_lin
ka_lin

Reputation: 9432

You can pass an array to the where method:

$this->_data['news'] = PageContent::orderBy('created_at', 'desc')
->where(array('category_id'=>3,'status'=>1))
->first();

Upvotes: 2

Related Questions