【问题标题】:How to associate files to post with Laravel 5.6如何将要发布的文件与 Laravel 5.6 关联
【发布时间】:2019-06-18 09:41:01
【问题描述】:

我在我的网络应用程序中使用 Laravel,我想用他自己的形式将文件与我的帖子以独立的方式关联,但我遇到了一些问题

我的路线(我正在使用身份验证控制包,但实际上我是管理员):

Route::post('file', 'fileController@store')->name('file.store')
    ->middleware('permission:file.create');
Route::get('file', 'fileController@index')->name('file.index')
    ->middleware('permission:file.index');
Route::get('file/create/', 'fileController@create')->name('file.create')
    ->middleware('permission:file.create');
Route::put('file/{id}', 'fileController@update')->name('file.update')
    ->middleware('permission:file.edit');
Route::get('file/{id}', 'fileController@show')->name('file.show')
    ->middleware('permission:file.show');
Route::delete('file/{id}', 'fileController@destroy')->name('file.destroy')
    ->middleware('permission:file.destroy');
Route::get('file/{id}/edit', 'fileController@edit')->name('file.edit')
    ->middleware('permission:file.edit');
Route::get('download/{filename}', 'fileController@download')->name('file.download')
    ->middleware('permission:file.download');

我的迁移:

    Schema::create('files', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('files_id')->unsigned();
        $table->string('filenames');
        $table->integer('fileable_id')->unsigned();
        $table->string('fileable_type');
        $table->timestamps();
    });

我的文件模型:

class File extends Model
{
protected $fillable = [
    'filenames', 'project_id'
];

public function user()
{
    return $this->belongsTo(User::class);
}

我的项目模型:

public function files()
{
    return $this->morphMany(File::class, 'fileable')->whereNull('files_id');
}

要存储的控制器:

class FileController extends Controller
{
public function store(Request $request)
{
    $this->validate($request, [
            'filenames' => 'required',
            'project_id' => 'required',
            // 'filenames.*' => 'mimes:doc,pdf,docx,zip'
    ]);

    if($request->hasfile('filenames'))
    {
        foreach($request->file('filenames') as $file)
        {
            $name=$file->getClientOriginalName();
            $file->move(public_path().'/files/', $name);  
            $data[] = $name;  
        }
    }

    $file= new File();
    $file->filenames = $request->get('filenames');
    $file->filenames= $name;
    $file->user()->associate($request->user());
    $project = Project::findOrFail($request->get('project_id'));
    $project->files()->save($file);
    $file->save();

    return back();
}

public function download( $filename = '' ) { 
// Check if file exists in storage directory
$file_path = public_path() . '/files/' . $filename;  

if ( file_exists( $file_path ) ) { 
    // Send Download 
    return \Response::download( $file_path, $filename ); 
    } else { 
    return back()->with('info', 'Archivo no existe en el servidor');
    }
}

刀片中的表单:

<form method="post" action="{{ route('file.store') }}" enctype="multipart/form-data">
<div class="input-group hdtuto control-group lst increment" >
  <input type="file" name="filenames[]" class="myfrm form-control">
  <input type="hidden" name="project_id" value="{{ $project->id }}" />
  <div class="input-group-btn"> 
    <button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
  </div>
</div>

<button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
</form>

Foreach 下载文件:

@foreach($project->files as $file)
  <li>{{ $file->user->name }}: <a href="{{ url('/download/')}}/{{$file->filenames}}" download> {{$file->filenames}}</a></li>
@endforeach

我从 Project Controll 发送文件

【问题讨论】:

  • $project = Project::find($request-&gt;get('project_id')); 如果返回的是null,则不能调用$project-&gt;files() ...。检查 $request-&gt;get('project_id') 包含的内容,并确保您拥有该 ID 的 Project

标签: php html laravel file-upload


【解决方案1】:

您收到第一条错误消息的原因是因为您从Request 获得的ProjectidDatabase 中找不到并返回null 而不是object。这意味着您确实在null 上调用files() 方法。要解决此问题,有多个步骤。

1.) 确保 project_id 始终位于 Request 内:

$this->validate($request, [
    'filenames' => 'required',
    'project_id' => 'required',
    // 'filenames.*' => 'mimes:doc,pdf,docx,zip'
]);

2.) 确保在从数据库中检索project 后检查它是否存在,这可以通过两种方式完成。

a) 您可以通过findprojectthrow an Exception(如果找不到):

$project = Project::findOrFail($request->get('project_id');`

b) 你可以用一个简单的 if 语句检查它是否不存在并做一些事情

$project = Project::find($request->get('project_id');
if (!$project) {
    // Project not found in database
    // Handle it
}

【讨论】:

  • 我添加了代码findOrFail,表单将文件保存在public_path()中。 '/files/',但不在数据库中创建记录
  • 您的use 是否在Controller 的顶部找到了正确的类File
  • 另外,您需要$file-&gt;save(); 才能创建File object inside the database 并能够创建link $file with $project,因为files()-&gt;save($file) 依赖于$file-&gt;id,它是在$file-&gt;save() 上创建的不早于
  • 就是这样!好好工作,终于。谢谢你。我会用正确的数据为其他人更改帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2018-10-18
  • 2011-09-02
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多