Permalink
Browse files

Episode 42

  • Loading branch information...
JeffreyWay committed May 19, 2017
1 parent d6b7800 commit 351d30bff1d34b26c16e544239523b6b6ca76013
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers;
use App\Thread;
class ThreadSubscriptionsController extends Controller
{
/**
* Store a new thread subscription.
*
* @param int $channelId
* @param Thread $thread
*/
public function store($channelId, Thread $thread)
{
$thread->subscribe();
}
/**
* Delete an existing thread subscription.
*
* @param int $channelId
* @param Thread $thread
*/
public function destroy($channelId, Thread $thread)
{
$thread->unsubscribe();
}
}
@@ -24,6 +24,13 @@ class Thread extends Model
*/
protected $with = ['creator', 'channel'];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['isSubscribedTo'];
/**
* Boot the model.
*/
@@ -98,4 +105,50 @@ public function scopeFilter($query, ThreadFilters $filters)
{
return $filters->apply($query);
}
/**
* Subscribe a user to the current thread.
*
* @param int|null $userId
*/
public function subscribe($userId = null)
{
$this->subscriptions()->create([
'user_id' => $userId ?: auth()->id()
]);
}
/**
* Unsubscribe a user from the current thread.
*
* @param int|null $userId
*/
public function unsubscribe($userId = null)
{
$this->subscriptions()
->where('user_id', $userId ?: auth()->id())
->delete();
}
/**
* A thread can have many subscriptions.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function subscriptions()
{
return $this->hasMany(ThreadSubscription::class);
}
/**
* Determine if the current user is subscribed to the thread.
*
* @return boolean
*/
public function getIsSubscribedToAttribute()
{
return $this->subscriptions()
->where('user_id', auth()->id())
->exists();
}
}
@@ -0,0 +1,15 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ThreadSubscription extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
@@ -0,0 +1,39 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateThreadSubscriptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('thread_subscriptions', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('thread_id');
$table->timestamps();
$table->unique(['user_id', 'thread_id']);
$table->foreign('thread_id')
->references('id')
->on('threads')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('thread_subscriptions');
}
}
Oops, something went wrong.

0 comments on commit 351d30b

Please sign in to comment.