jeudi 1 décembre 2016

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')

Current error:

Trying to get property of non-object.

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');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire