Permalink
Browse files

Episode 77

  • Loading branch information...
JeffreyWay committed Sep 6, 2017
1 parent a76952a commit be87b82cc3de098d4e1df298c11e72e8fb4ea237
@@ -68,10 +68,13 @@ public function store(Request $request)
'user_id' => auth()->id(),
'channel_id' => request('channel_id'),
'title' => request('title'),
'body' => request('body'),
'slug' => request('title')
'body' => request('body')
]);
if (request()->wantsJson()) {
return response($thread, 201);
}
return redirect($thread->path())
->with('flash', 'Your thread has been published!');
}
@@ -42,6 +42,10 @@ protected static function boot()
static::deleting(function ($thread) {
$thread->replies->each->delete();
});
static::created(function ($thread) {
$thread->update(['slug' => $thread->title]);
});
}
/**
@@ -191,28 +195,9 @@ public function getRouteKeyName()
public function setSlugAttribute($value)
{
if (static::whereSlug($slug = str_slug($value))->exists()) {
$slug = $this->incrementSlug($slug);
$slug = "{$slug}-{$this->id}";
}
$this->attributes['slug'] = $slug;
}
/**
* Increment a slug's suffix.
*
* @param string $slug
* @return string
*/
protected function incrementSlug($slug)
{
$max = static::whereTitle($this->title)->latest('id')->value('slug');
if (is_numeric($max[-1])) {
return preg_replace_callback('/(\d+)$/', function ($matches) {
return $matches[1] + 1;
}, $max);
}
return "{$slug}-2";
}
}
@@ -15,7 +15,7 @@ public function up()
{
Schema::create('threads', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique();
$table->string('slug')->unique()->nullable();
$table->unsignedInteger('user_id');
$table->unsignedInteger('channel_id');
$table->unsignedInteger('replies_count')->default(0);
@@ -3,7 +3,6 @@
namespace Tests\Feature;
use App\Activity;
use App\Thread;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
@@ -82,17 +81,25 @@ function a_thread_requires_a_unique_slug()
{
$this->signIn();
$thread = create('App\Thread', ['title' => 'Foo Title', 'slug' => 'foo-title']);
$thread = create('App\Thread', ['title' => 'Foo Title']);
$this->assertEquals($thread->fresh()->slug, 'foo-title');
$this->assertEquals($thread->slug, 'foo-title');
$this->post(route('threads'), $thread->toArray());
$thread = $this->postJson(route('threads'), $thread->toArray())->json();
$this->assertTrue(Thread::whereSlug('foo-title-2')->exists());
$this->assertEquals("foo-title-{$thread['id']}", $thread['slug']);
}
/** @test */
function a_thread_with_a_title_that_ends_in_a_number_should_generate_the_proper_slug()
{
$this->signIn();
$thread = create('App\Thread', ['title' => 'Some Title 24']);
$this->post(route('threads'), $thread->toArray());
$thread = $this->postJson(route('threads'), $thread->toArray())->json();
$this->assertTrue(Thread::whereSlug('foo-title-3')->exists());
$this->assertEquals("some-title-24-{$thread['id']}", $thread['slug']);
}
/** @test */

0 comments on commit be87b82

Please sign in to comment.