Вместо того, чтобы называть таблицу «files», я выбираю имя «items», потому что ресурс Nova таблицы будет иметь то же имя, что и «use Laravel \ Nova \ Fields \ File;».
Базовыйрешение вашей проблемы:
// database\migrations\2019_11_01_103838_create_items_table.php
Schema::create('items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('original_name',255);
$table->string('generated_name',255);
$table->timestamps();
});
// database\migrations\2019_11_01_104145_add_column_item_id_to_users_table.php
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('item_id')->nullable();
$table->foreign('item_id')->references('id')->on('items');
});
// app\Nova\User.php
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Gravatar::make(),
Text::make('Name')
->sortable()
->rules('required', 'max:255'),
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:254')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Password::make('Password')
->onlyOnForms()
->creationRules('required', 'string', 'min:8')
->updateRules('nullable', 'string', 'min:8'),
File::make('Item file')
->store(function (Request $request, $model) {
$oldName = $request->item_file->getClientOriginalName();
$newName = 'user_file_'.$oldName;
// Check file of user is exist or not
$user = \App\User::where('email',$request->email)->first();
if(!$user){
$item = new \App\Item;
$item->original_name = $oldName;
$item->generated_name = $newName;
$item->save();
$model['item_id'] = $item->id;
}else{
$item = \App\Item::find($user->item_id);
if(!$item){
$item = new \App\Item;
$item->original_name = $oldName;
$item->generated_name = $newName;
$item->save();
$model['item_id'] = $item->id;
}else{
$item->original_name = $oldName;
$item->generated_name = $newName;
$item->save();
}
}
// return $newName;
$request->item_file->storeAs('public',$newName);
})
->onlyOnForms(),
Text::make('Item File Id','item_id')->exceptOnForms()
];
}
// app\Observers\UserObserver.php = To delete the variable $model['item_file'] generate by File::make('Item file') in field User Nova resources.
<?php
namespace App\Observers;
use App\User;
class UserObserver
{
public function saving(User $user)
{
unset($user->item_file);
}
}
// app\Providers\AppServiceProvider.php = To register the UserObserver
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Observers\UserObserver;
use App\User;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
}