代码读取帖子中的主题标签并将其保存在数据库中。
if($post)
{
preg_match_all('/#(\w+)/', $request->get('body'),$tagNames);
// $tagnames contains an array of results. $tagnames[0] is all matches
$tagIds = [];
foreach($tagNames[0] as $tagName)
{
//$post->tags()->create(['name'=>$tagName]);
//Or to take care of avoiding duplication of Tag
//you could substitute the above line as
$tag = Tag::firstOrCreate(['name'=>$tagName]);
if($tag)
{
$tagIds[] = $tag->id;
}
}
$post->tags()->sync($tagIds);
}
现在我想让帖子中的标签可点击。怎么可能?可以在/ tags / id。
下调用标记中的视图答案 0 :(得分:2)
创建href基于标记id的锚元素。几个例子:
// loop the tags
@foreach ($post->tags as $tag)
<a href="{{ url(sprintf('tags/%d', $tag->id)) }}">I'm a tag link</a>
@endforeach
// or directly access the first one
<a href="{{ url(sprintf('tags/%d', $post->tags->first()->id)) }}">I'm a tag link</a>
<强>更新强>
在将帖子发送到视图之前处理帖子,将#username
文本替换为相应的标签。
$postall = $user->posts()->with('comments')->where('status', 1)->latest()->get();
$postall = $postall->map(function ($post, $key) {
// $post->tags->pluck('name') is an array of #replaceme strings. example: ['#bill', '#joe', '#sally']
// $links is an array of <a href="..">...</a>
$links = $post->tags->map(function ($tag, $key) {
return sprintf('<a href="/tags/%d">%s</a>', $tag->id, $tag->name);
});
return str_replace($post->tags->pluck('name'), $links, $post)
});
return return view('profiles.profile', compact('postall', 'followers', 'followings'));
然后在您看来:{!! $post !!}
请注意用户输入的数据,并采取任何必要的预防措施来防止SQL注入。