Category Archives: Laravel

can() not work for User Model (Laravel 5.1)

https://laravel.com/docs/5.1/authorization#via-the-user-model

Model User must have a trait:

use Illuminate\Foundation\Auth\Access\Authorizable;

Policy Example

<?php

namespace App\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;

use App\User;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function before($user, $ability){
        if ($user->isSuperAdmin()) {
            return true;
        }
    }

    public function view(User $user){
        if($user->is_admin() == true){
            return true;
        }

        return false;
    }
}

Usage in controller

$user = Auth::user();

// Need to pass $user!
logg($user->can('view', $user));

Reference:

網站使用API存取資料問題

如果是同一個系統,如果把資料存取從controller->model改成controller->api 會有以下問題

  • 增加額外的API開發及管理成本
  • Debug難度變高
  • 開發速度慢
  • Guzzle及postman不支援.host檔的設定,所以不能用 example.test 之類的網址存取API

結論: 不要用API

migrate not work

Error

Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found

Solution

  • Change version of “doctrine/dbal” to “^2.0”
    “doctrine/dbal”: “^2.0”,
  • composer update

Eloquent’s save() is not working

Following script will save nothing:

$member = MemberM::where('id', auth::id())
            ->select(
                "name",
                "email",
                "phone",
                "county",
                "district",
                "address",
                "verified", 
                'registered'
                )
            ->first();
$member->registered = 0;
$member->save();

Reason:

Because no primary column in select(), adding “id” column will save this problem.