首页 > 解决方案 > 在 laravel 中提供页面的链接

问题描述

我有一个问题数据库,可以在 localhost:8000/questions/{id} 中查看。我在现有的 laravel 项目中创建了一个聊天机器人。现在,我想向用户提供问题的链接。例如,如果我想要一个 id=55 的问题的链接,那么机器人必须使用链接 localhost:8000/questions/55 回复我。我怎么做?

网页.php

Route::resources([ 'questions' => 'QuestionController', ]); 
Route::match(['get', 'post'], '/botman', 'BotManController@handle'); 

QuestionController.php

public function show(Question $question) { 
    return view('question')->with('question', $question); 
} 

botman.php

use BotMan\BotMan\BotMan; 
use BotMan\BotMan\BotManFactory; 
use BotMan\BotMan\Cache\DoctrineCache; 
use BotMan\BotMan\Drivers\DriverManager; 
use App\Conversations\StartConversation; 

DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class); 
$cachedriver = new Doctrine\Common\Cache\PhpFileCache('cache'); 
BotManFactory::create(config('botman', new 
DoctrineCache($cachedriver))); 
$botman = app('botman'); 
$botman->hears('Hello|Hi', 
       function($bot) { 
          $bot->typesAndWaits(1); 
          $bot->startConversation(new StartConversation); 
       }
);

BotManController.php

<?php 

namespace App\Http\Controllers;

use Illuminate\Http\Request; 
use BotMan\BotMan\BotMan; 
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Messages\Conversations;
use App\Conversations\StartConversation; 

class BotManController extends Controller { 
    public function handle() { 
        $botman = app('botman'); 
        $botman->listen(); 
    } 
    public function startConversation(Botman $bot) { 
        $bot->startConversation(new StartConversation()); 
    }
}

标签: laravel-5routes

解决方案


首先,我们从问题表中获取所有 id:

$questions   = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->get();

$ids 这里是 id 的集合,所以我们必须为每个 id 创建一个链接:

$links = array();
foreach($questions as $question){
     $links[] = route('questions.show', ['id' => $question->id]);
}

所以现在我们有所有需要作为答案返回的链接,使用$this->say...完成它,如你所愿


您可能希望返回第一个链接而不是所有链接,然后从数据库中获取第一个 id 并使用它创建链接:

$question = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->first()
$link = route('questions.show', ['id' => $question->id]);

然后使用返回答案$this->say

我希望这有帮助


推荐阅读