[英]Laravel Voyager overwrite BREAD controller
我已經開始使用Voyager,但控制器出現問題。
我已經在數據庫中創建了一個名為Progress的新表,默認情況下,voyager會創建一個BREAD表單來瀏覽讀取的刪除和添加項。
我喜歡在用戶去添加新項目時在字段中輸入默認值。 我要輸入的默認值是身份驗證user_id
我怎樣才能做到這一點?
謝謝。
您可以完全在Voyager之外執行此操作。
首先從“添加”表單(在Voyager的數據庫界面中)中排除authentication_user_id
。 如果該字段不使用空值,則可以設置一些臨時默認值,或修改您的遷移-以最方便的為准。
接下來,創建一個模型觀察器 ,然后利用created()
函數。 例如:
<?php
namespace App\Observers;
use App\Models\Project;
class ProgressObserver
{
/**
* Listen to the Progress created event.
*
* @param Progress $progress
* @return void
*/
public function created(Progress $progress)
{
$progress->authentication_user_id = WHATEVER_YOU_DO_HERE;
$progress->save();
}
}
我認為您可以創建遷移以為該字段寫入默認值
為面包創建模型后,可以創建一個名為save
的函數。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Auth;
class MyViewModel extends Model
{
//
protected $table = "my_view";
public function save(array $options = [])
{
$this->user_id = \Auth::user()->id;
parent::save();
}
}
現在,每當您在voyager的管理中保存任何記錄時,您都會看到當前登錄用戶ID被保存在數據庫表中。
您必須像這樣將以下代碼添加到模式中,
//assign created_by loggedin user
public function __construct(array $attributes = [])
{
$this->creating([$this, 'onCreating']);
parent::__construct($attributes);
}
public function onCreating($row)
{
// Placeholder for catching any exceptions
if (!\Auth::user()->id) {
return false;
}
$row->setAttribute('created_by', \Auth::user()->id);
$row->setAttribute('assign_to', \Auth::user()->id);
}
我已經添加了這個,因為我的項目需要這個。 您還可以在onCreating()函數中添加字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.