【Laravel入門】10分鐘做出Laravel專案的自有站內搜尋

【Laravel入門】10分鐘做出Laravel專案的自有站內搜尋

這個套件能為你的應用裡頭的 Eloquent 模型加入全文搜尋功能

安裝&設定 Scout 套件

Step 1.下載 Scout 套件

透過 Composer 來下載套件檔案

composer require laravel/scout

Step 2.發布設定檔到專案內

下面命令將會在 config 資料夾內新增一個 scout.php 設定檔

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Step 3.加入 Searchable trait

在要加入全文搜尋的模型類別內加入 Searchable trait

//app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;
}

Step 4.安裝 Algolia Driver

Scout套件需要有個搜尋Driver,推薦使用Saas服務 Algolia,需要先安裝其Driver,同樣透過composer來下載

composer require algolia/algoliasearch-client-php

Step 5(非必須).註冊 Algolia 帳號

Algolia官網

你也可以利用Google或Github來做SSO

Step 6.設定ID與金鑰

開啟 .env 檔案,加入以下設定

ALGOLIA_APP_ID=應用ID
ALGOLIA_SECRET=金鑰

要取用ID和金鑰,需要進入Algolia後台

Step 7.模型設定

設定模型Index

Algolia讓你能夠為每個表格去建立一個Index,你需要先到Algolia後台去建立之後,再回來模型去設定

//app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    /**
     * Get the name of the index associated with the model.
     *
     * @return string
     */
    public function searchableAs()
    {
        return 'posts_index';
    }
}

設定 Searchable Data

//app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        //score和price這兩個欄位不搜尋
        unset($array['score']);
        unset($array['price']);

        return $array;
    }
}

在控制器進行搜尋

//app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class PostController extends Controller
{

public function index()
{
 //透過 Algolia 進行搜尋
 $queryData = Post::search()->get();
 ...
}

辨識使用者

如果希望使用者在使用搜尋功能時能夠識別他的身份,可透過加入以下設定到.env裡頭去開啟這個功能

SCOUT_IDENTIFY=true

參考資料

官方文件


分享這篇文章:

關聯文章:

訂閱電子報,索取 Laravel 學習手冊

價值超過 3000 元,包含常用 Laravel 語法與指令!

Laravel 百萬年薪特訓營

從最基礎的 PHP 語法開始,包含所有你該知道的網頁基礎知識,連同 Laravel 從零開始一直到實戰,最後還將告訴你如何找好工作,讓你及早擁有百萬年薪