0

Migration class CreatePostsTable extends Migration

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->text('number')->nullable();
        $table->text('text');
        $table->boolean('is_approved')->default(0);
        $table->timestamp('published_at');
        $table->timestamps();
        $table->softDeletes();
    });
}

model Post

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'text',
        'number'
    ];

    protected $dates = ['published_at', 'deleted_at'];

    public function setPublishedAtAttribute($date) 
    {
        $this->attributes['published_at'] = Carbon::now('Europe/Moscow');
    }

    public function scopeApproved($query) 
    {
        $query->where('is_approved', '==', '1');
    }
}

Controller HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Post;

class HomeController extends Controller
{
    public function index() {
        $posts = Post::latest('published_at')->approved()->paginate(20);
        return view('home.index', compact('posts'));
    }
}

So it is expected that on the Home page I receive only approved posts but instead all posts are shown on the page. What's wrong?

1 Answer 1

3

Your scope uses the == operator, which is great for php, but since the operator will be used in the query you need just a regular equal sign:

$query->where('is_approved', '=', '1');

Or just

$query->where('is_approved', 1);
Sign up to request clarification or add additional context in comments.

1 Comment

Well, in previous versions of Laravel $query->where('is_approved', '==', '1'); worked just fine, I didn't know it changed. Thanks a lot for the help, $query->where('is_approved', 1); works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.