controller 的返回结果中有<a>标签,如何将带 id 的 route 作为<a>标签的 href 值传到 view 中

在controller的返回结果中有<a>标签,如何将带id的route作为<a>标签的”href”值传到view中。
如下代码,这个是在SearchCcontrolle.php里面的对于搜索结果处理的代码。

public function search(Request $request){
        if($request->ajax()){
            $output = '';
            $product = DB::table('books')->where('name','LIKE','%'.$request->search.'%')->get();
            if($product){
                foreach($product as $key => $product){
                    $output.='<tr>'.
                    '<td>'.'<a class="links" href="'.route('books.show',['id' => ($product -> id)]).'" >'.$product -> id.'</a></td>'.
                     '<td>'.
                        '<a href="'.route('book_requests.create').'" >'.
                            '<button class="btn btn-my" type="submit">Request</button>'.
                        '</a>'.
                    '</td>'.
                    '</tr>';
                }
                return Response($output);
            }
        }
    }

在上面这段代码中,第一个<td>中想返回一个<a>标签,这个<a>标签的href值是一个带id的route,但是用我目前的写法不会报错,但是实际测试的时候,点击对应的<td>中的<a>,返回url是这个样子的:
(http://localhost:8000/%7B%7Broute('books.s...)
在web.php文件中,我对于books.show的定义如下:

Route::get('/books/{id}', 'BookController@show')->name('books.show');

其他功能都正常,不带id的route(例如第二个<td>)没有问题,功能也正常,但是这个带id的route真的搜了好久都没有看到相应的解决办法,想请教一下大家,关于这个应该要怎么正确地传值

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 5

这段代码不建议这样写。用视图比较好。

   $output.='<tr>'.
                    '<td>'.'<a class="links" href="'.route('books.show',['id' => ($product -> id)]).'" >'.$product -> id.'</a></td>'.
                     '<td>'.
                        '<a href="'.route('book_requests.create').'" >'.
                            '<button class="btn btn-my" type="submit">Request</button>'.
                        '</a>'.
                    '</td>'.
                    '</tr>';
3年前 评论

都用laravel了,还这样写,属实对不起laravel的优雅了

3年前 评论

route('books.show', $product->id) 即可

3年前 评论

url('/book/' . $product->id)

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!