Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
帖子中的可点击标签-Laravel_Laravel_Url_Routes_Tags_Hashtag - Fatal编程技术网

帖子中的可点击标签-Laravel

帖子中的可点击标签-Laravel,laravel,url,routes,tags,hashtag,Laravel,Url,Routes,Tags,Hashtag,代码读取post中的hashtag并将其保存在数据库中 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 $

代码读取post中的hashtag并将其保存在数据库中

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下调用。

创建锚元素,其中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>
然后在您的视图中:
{!!$post!!}


但是要注意用户输入的数据,并采取任何必要的预防措施防止sql注入。

在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>
然后在您的视图中:
{!!$post!!}


不过要注意用户输入的数据,并采取必要的预防措施防止sql注入。

谢谢,这是个好主意。但是标签应该直接链接到文本中,而不是额外链接到文本中。示例:我的名字是,而不是。您如何知道标签在文本中的位置?您是否有占位符或某种标记指示链接的放置位置?标记用#标记。正如您在上面的代码中所看到的,所有单词都在单词As标记前用#保存。您是否将
$request->get('body')
存储在数据库中?body存储在表“post”中的数据库中。还有一张额外的桌子上的标签,有很多到五月的关系谢谢,这是个好主意。但是标签应该直接链接到文本中,而不是额外链接到文本中。示例:我的名字是,而不是。您如何知道标签在文本中的位置?您是否有占位符或某种标记指示链接的放置位置?标记用#标记。正如您在上面的代码中所看到的,所有单词都在单词As标记前用#保存。您是否将
$request->get('body')
存储在数据库中?body存储在表“post”中的数据库中。以及具有多对多关系的额外表中的标记