【问题标题】:Append $id to post slug on create in Laravel附加 $id 以在 Laravel 中的 create 上发布 slug
【发布时间】:2018-09-26 10:23:56
【问题描述】:

我正在使用 Laravel 从表单创建博客文章,并将标题和正文传递给 PostsController 中的 create 方法。

蛞蝓必须是唯一的,所以虽然下面的方法有效,但当我使用重复的标题时它会失败。

我打算将 $post->id 附加到 slug,所以 this-is-the-post-title 将变为 this-is-the-post-title-12

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Session;
use Carbon\Carbon;

class PostController extends Controller
{
  public function store(Request $request) {
  $this->validate($request, [
    'title' => 'required|max:255',
    'body'  => 'required'
  ]);

  $post = new Post;
  $post->title = $request->input('title');
  $post->body = $request->input('body');
  $post->slug = str_slug($request->input('title'), '-');
  $post->save();

  Session::flash('success', 'The blog post was successfully saved!');

  return redirect()->route('posts.show', $post->id);
}

我最初的想法是将 $post-&gt;id 连接到 slug 的末尾,但它不起作用。

我假设这是因为 id 直到 save() 才被分配?

有没有办法获取要使用的 id?

我想只返回数据库中的行数,然后添加一个,但如果两个人同时发帖,那就失败了。

(我对 Laravel 还很陌生,并且自学了 PHP,所以这可能非常明显/简单,但感谢任何帮助。)

【问题讨论】:

    标签: php laravel slug laravel-5.6


    【解决方案1】:

    先保存后更新:

    $post = \DB::transaction(function() use($request) {
        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->slug = uniqid(); //to avoid unique column conflict, it will be overwritten
        $post->save();
    
        $post->slug = str_slug($request->input('title').' '.$post->id, '-');
        $post->save();
    
        return $post;
    });
    

    【讨论】:

    • 如果 slug 列具有唯一约束,则必须小心输入 'anything' 的内容。除此之外,这应该可以工作。
    • 太好了,谢谢。我最初是这样做的,但它失败了。我现在意识到我使用“测试帖子”作为标题,但它失败了,因为我已经在数据库中有一个 test-post slug。截断表格后,这意味着我根本无法将 'test-post' 作为 slug,因为它会自动附加 id。
    • 回到上面的答案,如果我将帖子命名为“post 2”并且已经有一个带有 slug 的帖子post-2
    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2014-10-23
    相关资源
    最近更新 更多