Posted on Leave a comment

SaaS with laravel (4)-租户功能增加

新增独立路由:routes/account.php

<?php

// access route names as tenant.account.profile.* e.g. tenant.account.profile.edit
// access route path as account/profile/* e.g. account/profile/edit
Route::group(['prefix' => 'profile'], function () {
    Route::get('/', 'ProfileController@edit')->name('profile.edit'); // show profile edit form
    Route::patch('/', 'ProfileController@update')->name('profile.update'); // edit profile
});

修改 app/Providers/RouteServiceProvider.php

public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    $this->mapTenantRoutes(); // add this call
}
/**
 * Definte the "tenant" routes for the application.
 *
 * These routes should be aliased as tenant.x to make it explicit when referring
 * from view. This would help remove confusion in the future when we have
 * "system" routes. Think of it as a namespace for the routes.
 */
protected function mapTenantRoutes()
{
    Route::middleware(['web', 'auth'])
        ->namespace($this->namespace)
        ->as('tenant.account.')
        ->prefix('account')
        ->group(base_path('routes/account.php'));
}

增加功能,增加controller: app/Http/Controllers/ProfileController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateProfileRequest;

class ProfileController extends Controller
{
    public function edit()
    {
        return view('tenant.account.profile');
    }
}

新增页面 resources/views/tenant/account/profile.blade.php :

CRUD 增删改查功能:

...
public function update(UpdateProfileRequest $request)
{
    $request->commit();
    session()->flash('alert', ['type' => 'success', 'message' => 'Your profile has been updated.']);

    return redirect(route('tenant.account.profile.edit'));
}
...

Request验证类:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class UpdateProfileRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name'  => 'required',
            'email' => ['required', Rule::unique('tenant.users')->ignore(Auth::id())],
        ];
    }

    public function commit()
    {
        $this->user()->update(['name' => $this->name, 'email' => $this->email]);
    }
}

//注意 数据表 是 : tenant.users

commit() 是 更新 用户 时候 适用

Leave a Reply

Your email address will not be published. Required fields are marked *