我目前正在构建一个评论系统,并希望包括提及用户和标记他们的功能,随后我希望该标签具有指向他们个人资料的链接(在本例中,它只是/profile/{id })
我目前正在使用 Laravel Mentions 从我的用户模型生成自动填充列表。我这样做是这样的:
function enableMentions(elem, type, column) {
$(elem).atwho({
at: "@",
limit: 5,
displayTpl: '<li><span>${name}</span></li>',
insertTpl: '<a href="/profile/${name}" data-type="mentionable" data-id="${id}" data-name="${name}">${name}</a>',
callbacks: {
remoteFilter: function(query, callback) {
if (query.length <= 1) return;
$.getJSON("/api/mentions/" + type, {
q: query,
c: column
}, function(data) {
callback(data);
});
}
}
});
}
// My api/mentions route: Route::get('/api/mentions/{type}', 'ApiController@index');
//My api controller:
public function index($type, Request $request)
{
try {
$resultColumns = [];
$query = $request->get('q');
$column = $request->get('c');
$model = app()->make(config('mentions.' . $type));
$records = $model->where($column, 'LIKE', "%$query%")
->get();
foreach ($records as $record) {
$resultColumns[] = $record->$column;
}
return response()->json($resultColumns);
} catch (\ReflectionException $e) {
return response()->json('Not Found', 404);
}
}
And finally, initializing the at.js
<script type="text/javascript">
$(function(){
enableMentions("#mention-commentContent", "users", "Username");
});
</script>
<div contentEditable="true" id="mention-commentContent" class="user-form" name="commentContent" type="text"></div>
我对如何修改上面的内容以返回分配给他们的用户名和 ID 感到困惑,这样我就可以将 ${name} 更改为 ${id} 并将其链接到他们的个人资料,对吧?
最佳答案
这个包可能有帮助 Laravel Mentions或 this .
基本思想是通过 JSON 从数据库中获取用户名,以下是他们在 laracasts 中的使用方式:
$("textarea#body").atwho({
at: "@", limit: 5, callbacks: {
remoteFilter: function (t, e) {
t.length <= 2 || $.getJSON("/api/users", {q: t}, function (t) {
e(t)
})
}
}
})
关于javascript - 使用 Laravel Mentions(at.JS 和 Laravel)返回用户名及其 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35799551/