Thursday, March 16, 2017

return all the posts where author.username equals $username

I have a posts model that has this relationship to the User:

public function author()
{
    return $this->belongsTo(User::class, 'user_id');
}

i am building a search function and I have this code

public function index(Request $request)
{
    $search = $request->search;
    $filter = $request->filter;

    $append = array();

    $posts = Post::with('author')->with('categories')->latest();

    if($search){
        switch ($filter) {
            case 'username':
                $posts->author->where('username', 'LIKE', '%'. $search . '%');
            break;
        }
        $append += array('search' => $search);
        $append += array('filter' => $filter);
    }

    $posts = $posts->paginate(3);
    $posts->appends($append);

    return view('core.blog.posts.index', compact('posts'));
}

I get

Undefined property: Illuminate\Database\Eloquent\Builder::$author

How do I add where that looks for author based on his username? I must be able to add this condition in an if case



via maxit

Advertisement