PHP Developer
PHP Developer

Reputation: 13

How to make Highlight for search results by Laravel 5.2?

in view:

@if($posts)
            @foreach($posts as$post)
                <h2>
                    <a href="{{route('home.post',$post->id)}}">{{$post->title}}</a>
                </h2>
                <p class="lead">
                    by <a href="index.php">{{$post->user->name}}</a>
                </p>
                <p><span class="glyphicon glyphicon-time"></span> Posted {{$post->created_at->diffForHumans()}}</p>
                <hr>
                <img class="img-responsive" src="{{$post->photo->file}}" alt="">
                <hr>
                {!! str_limit($post->body,35 )!!}
                <a class="btn btn-primary" href="{{route('home.post',$post->id)}}">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
                <hr>
            @endforeach
        @endif

in controller:

public function searchmulti(){
        $keyword=Input::get('title');
        $posts = Post::where('title', 'like', "%$keyword%")->get();
        return view('Admin.comments.postsauthor',compact('posts'));
       }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Upvotes: 0

Views: 1599

Answers (1)

neuronet
neuronet

Reputation: 1159

convert search result to array with toArray() method (see here) and then iterate through results and use str_replace to replace searched word with <span class="highlight">your word</span>

after this you will have $post['title'] (instead of $post->title) with highlighted span inside

of course you must add .highlight with some styling in your css

$posts = Post::where('title', 'like', "%$keyword%")->get()->toArray();
foreach($posts as &$post){
  $post['title']=str_replace($keyword,"<span class='highlight'>$keyword</span>",$post['title']);
}

PS if you don't want to convert results to array you can edit tile in eloquent model directly but I prefer arrays to be certain that I don't save changes accidently

Upvotes: 1

Related Questions