2016-06-22 68 views
1

因此,我正在學習laravel並嘗試設置阻止的用戶列表,例如,如果您想阻止用戶查看您的個人資料,您將阻止他們,但是我已經完成了這一操作我只是想知道我做的方式是否正確。Laravel 5.2 Relationship hasMany with another unique identifier

以下是我所做的。我的主要問題是,是否有另一種方法來建立一個標識符而無需創建一個名爲unique_id的新數據庫字段,其中我將兩個用戶id放入並隨後每次查詢它。

數據庫遷移:

Schema::create('blocked_users', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->integer('user_id')->unsigned(); 
     $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
     $table->integer('blocked_user_id')->unsigned(); 
     $table->foreign('blocked_user_id')->references('id')->on('users')->onDelete('cascade'); 
     $table->integer('unique_id')->unique(); 
     $table->text('reason')->nullable(); 
     $table->timestamps(); 
    }); 

用戶模型

public function BlockedUsers() 
{ 
    return $this->hasMany('App\Models\User\BlockedUsers'); 
} 

後來,當我阻止用戶我進入被阻止的用戶ID和當前用戶ID作爲UNIQUE_ID

然後這是我正在做的凌亂的部分,我相信應該有一個更簡單的方法。

if (BlockedUsers::whereUniqueId($user->id.Auth::user()->id)->exists()) { 
    $blocked = 1; 
} else { 
    $blocked = 0; 
} 

我試圖想辦法來建立用戶模型中的功能檢查,如果user_id是=當前用戶和blocked_user_id等於用戶配置文件ID。

所有我能想到的是

public function isUserBlocked() 
{ 
    return $this->hasOne('App\Models\User\BlockedUsers', 'blocked_user_id'); 
} 

但顯然這是行不通的。

回答

1

我認爲你可以照顧一些適用於該路線的中間件的內部。

php artisan make:middleware UserCanViewProfile 

然後我們假設中間件將應用到具有Profile模型的路線,比如這個:

Route::get('/profile/{profile}', '[email protected]'); 

現在,我們將在我們的中間件通過訪問獲取配置文件的實例它通過route,然後我們將檢查用戶是否有一個包含profile user idauth user id的塊。

$profile = $this->route('profile'); 
$$block = BlockedUsers::where('user_id', $profile->user->id)->where('blocked_user_id', auth()->user()->id)->first(); 

if (empty($block)) { 
    return $next($request);  
} else { 
    abort(403, 'You are not allowed to view that profile!'); 
} 

當然你需要在你App\Http\Kernel文件中註冊下$routeMiddleware這個中間件,像這樣:

'usercanviewprofile' => \App\Http\Middleware\UserCanViewProfile::class, 

然後將其應用到你的routes

Route::group(['middleware' => ['usercanviewprofile'], 'prefix' => 'profile'], function(){ 
    Route::get('{profile}', '[email protected]'); 
}); 

或者,如果你'使用CRUD模式:

Route::resource('profile', 'ProfileController')->middleware('usercanviewprofile'); 

希望這會有所幫助。

+0

我真的很抱歉,我已經設置了檢查用戶是否被阻止的方式,我只是想知道我做的方式是否正確。我已經這樣做了,但我只是想知道我做的這個方法是否正確。 「以下是我所做的,我的主要問題是,是否有另一種方法來建立一個標識符而無需創建一個名爲unique_id的新數據庫字段,其中我將兩個用戶id放在一起,然後每次查詢它」 –

+0

@ Unifx是的,我上面列出的方法並不需要這些。 – Ohgodwhy

+0

對不起,我沒有看到那部分,再次感謝 –