Routers

1
2
3
4
5
6
<?php

Route::put('/list/friend/{mid}', 'ListController@friend_update');
Route::put('/list/friend/{mid}', 'ListController@friend_update1');
Route::put('/list/friend/{member_friend}', 'ListController@friend_update2');
Route::put('/list/friend/{member_friend}', 'ListController@friend_update3')->middleware('can:update,member_friend');

Policy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php

namespace App\Policies;

use App\Models\Member;
use App\Models\Member_Friend;
use Illuminate\Auth\Access\HandlesAuthorization;

class Member_FriendPolicy
{
    use HandlesAuthorization;

    public function __construct()
    {}

    public function update(Member $member, Member_Friend $member_friend) 
    {
        return $member->account_id === $member_friend->member_account_id;
    }
}

Controller

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php


/**
* 1. 一開始的程式碼
*/
public function friend_update(Request $request, int $mid)
{
    $result = $request->user()
        ->getFriends()
        ->where('member_account_id_detail', $mid)
        ->firstOrFail()
        ->update(['customname' => $request->customname]);

    return Common::jsonResponse(
        [ 'success' => true ],
        200
    );
}

/**
* 2. 嘗試套入簡單的policy方法
*/
public function friend_update1(Request $request, int $mid)
{
    $member_friend = Member_Friend::findOrFail($mid);
    if ($request->user()->cant('update', $member_friend)) {
        abort(403);
    }
    $member_friend->update(['customname' => $request->customname]);

    return Common::jsonResponse(
        [ 'success' => true ],
        200
    );
}

/**
* 3. 透過Route使用Member_Friend類別依賴注入
*/
public function friend_update2(Request $request, Member_Friend $member_friend)
{
    $this->authorize('update', $member_friend);
    $member_friend->update(['customname' => $request->customname]);

    return Common::jsonResponse(
        [ 'success' => true ],
        200
    );
}

/**
* 4. 在Route上middleware policy (can:policy_function,model)後
*/
public function friend_update3(Request $request, Member_Friend $member_friend)
{
    $member_friend->update(['customname' => $request->customname]);

    return Common::jsonResponse(
        [ 'success' => true ],
        200
    );
}