Reputation: 711
I'm creating a blog post from a form using Laravel, and passing the title and body through to the create
method in the PostsController
.
The slug has to be unique, so although the following works, it fails when I use a duplicate title.
I intended on appending the $post->id
to the slug, so this-is-the-post-title
would become 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);
}
My initial thought was to concatenate $post->id
to the end of the slug, but it doesn't work.
I'm assuming that this is because the id
isn't assigned until the save()
?
Is there a way to get the id that is going to be used?
I thought of just returning the number of rows in the db, and adding one, but that would fail if two people posted at the same time.
(I'm fairly new to Laravel and taught myself PHP, so this may be glaringly obvious/simple, but any help is appreciated.)
Upvotes: 0
Views: 1308
Reputation: 15131
Save first then update later:
$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;
});
Upvotes: 2