Home » Php » Laravel 4 where like clause

Laravel 4 where like clause

Posted by: admin November 30, 2017 Leave a comment

Questions:
    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

Answers:

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'));

}

Questions:
Answers:

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);

Questions:
Answers:

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