简体   繁体   中英

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. I am unable to retrieve the employee id after uploading the file to save it to the DB table as a foreign key. 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.

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

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

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

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.

How do I capture the 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. 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 ?? If I am understanding well EmpDocuments belongsTO Employees right??

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!! 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' ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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