简体   繁体   English

如何使Laravel控制器存储具有关系的文件上传

[英]How to make Laravel controller store file upload with a relationship

I am trying to store an uploaded file with a relationship to an Employee model. 我正在尝试存储与Employee模型相关的上传文件。 I am unable to retrieve the employee id after uploading the file to save it to the DB table as a foreign key. 上传文件以将其作为外键保存到数据库表后,我无法检索员工ID。 Routes: 路线:

Route::resource('employees', 'EmployeesController');
Route::post('documents', 'DocumentsController@createdocument')

So I am on a URL that says http://localhost/public/employees/8 when I hit upload it redirects to http://localhost/public/documents and the file does upload but shows error when writing to DB. 因此,当我单击上载时,我使用的URL上显示http://localhost/public/employees/8 ,它将重定向到http://localhost/public/documents ,文件确实上载,但在写入数据库时​​显示错误。

Here is my code. 这是我的代码。 How can I do it? 我该怎么做?

public function createdocument(Request $request, Employee $id)
{
    $file = $request->file('file');
    $allowedFileTypes = config('app.allowedFileTypes');
    $maxFileSize = config('app.maxFileSize');
    $rules = [
        'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
    ];
    $this->validate($request, $rules);


    $time = time();  // Generates a random string of 20 characters
    $filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with 
     $destinationPath = config('app.fileDestinationPath').'/'.$filename;
        $uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));

        if($uploaded){      
        $employee = Employee::find($id);            
        $empdoc = new EmpDocuments();
        $empdoc->name = $filename;
        $empdoc->employee_id = $employee->id;       
        $empdoc->save();

        }    
        return redirect('employees');
}

These are my models. 这些是我的模特。

Employee.php Employee.php

public function EmpDocuments()
    {
    return $this->hasMany('App\EmpDocuments');
    }

    public function createdocument(){
   return $this->EmpDocuments()->create([
          'name' => $filename,
          'employee_id' => $id,
          ]);
    }

EmpDocuments.php EmpDocuments.php

public function Employee()
    {
        return $this->belongsTo('App\Employee');
    }

With the above models and controller I am now getting error 使用上述模型和控制器,我现在遇到错误

General error: 1364 Field 'employee_id' doesn't have a default value (SQL: insert into empdocuments. 常规错误:1364字段'employee_id'没有默认值(SQL:插入empdocuments。

How do I capture the employee_id? 如何捕获employee_id?

Managed to fix it, in case someone has similar problem. 设法解决它,以防有人遇到类似问题。 Ensure you pass the id with the route action for it to be capture in the next request. 确保您将id与route操作一起传递,以便在下一个请求中将其捕获。 Here is the final controller. 这是最终的控制器。

public function update(Request $request, $id)
{    


    $file = $request->file('file');
    $allowedFileTypes = config('app.allowedFileTypes');
    $maxFileSize = config('app.maxFileSize');
    $rules = [
        'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
    ];
    $this->validate($request, $rules);


    $time = time();  // Generates a random string of 20 characters
    $filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with 
     $destinationPath = config('app.fileDestinationPath').'/'.$filename;
        $uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));



        if($uploaded){

        $employee = Employee::find($id);
        $empdoc = new EmpDocuments();
        $empdoc->name = $filename; 
        $employee->empdocuments()->save($empdoc);
        return redirect('employees/' . $id . '#documents')->with('message','Document has been uploaded');

        }
}

Do you have a relationship between Employee and EmpDocuments ?? Employee和EmpDocuments之间有关系吗? If I am understanding well EmpDocuments belongsTO Employees right?? 如果我对EmpDocuments属于TO员工的理解很好,对吗?

I'm trying to help but I need to understand, one employee can have many documents right?? 我正在尝试提供帮助,但我需要了解,一位员工可以拥有许多文件吗? but each document belongs to just one employee right?? 但是每个文档只属于一个雇员吗?

If is like that you should make a relationship in your employee model, 如果这样,您应该在员工模型中建立关系,

` public function employeeDocuments(){
      return $this->hasMany(EmpDocuments::class);
    }`   

Then in the same model 然后在同一模型中

`public function createEmployeeDocuments(){
   return $this->employeeDocuments()->create([
          'your_db_fields' =>your file,
          'your_db_fields' => your other some data, 
          ]);
  }`

The id will be inserted automatically I hope I helped you!! ID将自动插入,希望对您有所帮助!! https://laravel.com/docs/5.3/eloquent-relationships https://laravel.com/docs/5.3/eloquent-relationships

Are your fillable empty??? 您可填写的是空的吗??? To use the Eloquent create method you need to set you fillable array to mass assignment. 要使用雄辩的创建方法,您需要将可填充数组设置为批量分配。 Try this, if is still not working tell me and I will try to do my best. 尝试此操作,如果仍然无法运行,请告诉我,我将尽力而为。

protected $fillable = [ 'employee_id', 'Your_db_field', 'Your_db_field', 'per_page', 'Your_db_field', 'Your_db_field' ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM