2016-08-16 116 views
-1

在視圖:如何使Laravel 5.2的搜索結果突出顯示?

@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 

在控制器:

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

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

回答

0

將搜索結果轉換爲toArray()方法(see here)然後 迭代通過結果,並使用str_replace更換搜索詞與<span class="highlight">your word</span>

在這之後,你將有(而不是$post->title$post['title']與突出跨度內

當然

,你必須在你的CSS一些樣式添加.highlight

$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如果您不想將結果轉換爲數組,您可以直接在雄辯模型中編輯拼貼,但我更願意使用數組來確保不會意外地保存更改

+0

拜託,你能通過代碼告訴我這個嗎?在此先感謝 –

+0

我在編輯中添加了一些代碼,但此代碼未經測試 - 僅從內存 – neuronet

+0

我試過並顯示此錯誤:嘗試獲取非對象的屬性在視圖 –

相關問題