Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 692
harishannam Avatar asked Dec 20 '22 03:12

harishannam


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

}
like image 177
Vit Kos Avatar answered Dec 22 '22 17:12

Vit Kos


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);
like image 21
Kylie Avatar answered Dec 22 '22 15:12

Kylie