harishannam
harishannam

Reputation: 2796

Laravel 4 where like clause

    public function getIndex()
        {


// Get all the blog posts
        /*$posts = Post::with(array(
            'author' => function($query)
            {
                $query->withTrashed();
            },
        ))->orderBy('created_at', 'DESC')->paginate(10);*/


        $posts =Post::with(array('search' => function($query)
        {
            $query->where('title', 'like', '%Lorem ipsum%')->withTrashed();
        }))->orderBy('created_at', 'DESC')->paginate(10);


        // Show the page
        return View::make('frontend/blog/index', compact('posts'));

    }

This is my code in Controller. I am using a starter bundle available on GitHub.

I created this model for this controller

public function search()
{
    return $this->belongsTo('Post', 'user_id');
}

Problem is it is not taking the results where title contains "Lorem ipsum". It just prints all the values from the table.

How can i implement this to get only the values that contain my Tag/Keyword. I am doing this to add search option to the laravel site

Upvotes: 4

Views: 19763

Answers (3)

Vit Kos
Vit Kos

Reputation: 5755

Why not create a scope for this? Have you read scopes docs? Here is an example how would I have achieved that:

The scope:

public function scopeTagged($query, $tag)
{
    return $query->where('title', 'LIKE', '%' . $tag . '%');
}

And modification to your action:

public function getIndex()

{

    $posts = Post::tagged($lorem_ipsum)->withTrashed()->orderBy('created_at', 'DESC')->paginate(10);

    // Show the page
    return View::make('frontend/blog/index', compact('posts'));

}

Upvotes: 10

deepika jain
deepika jain

Reputation: 363

I think it was an issue with the Laravel Eager loading Constraints implementations:

For ref:-

https://github.com/laravel/laravel/pull/1069

https://github.com/laravel/laravel/pull/946

Upvotes: 0

Kylie
Kylie

Reputation: 11759

Try this...

    $posts =Post::with(array('search' => function($query)
    {
        $query->raw_where("title LIKE '%Lorem ipsum%")->withTrashed();
    }))->orderBy('created_at', 'DESC')->paginate(10);

Or something along these lines...

$search being your input

 Post::raw_where("match (`title`) against (?)", array($search))
    ->orderBy('created_at', 'DESC')->paginate(10);

EDIT

What about this?

 Post::where(DB::raw('MATCH(`title`)'),'AGAINST', DB::raw('("+'.implode(' +',$search).'" IN BOOLEAN MODE)->orderBy('created_at', 'DESC')->paginate(10);

Upvotes: 1

Related Questions