代码之家  ›  专栏  ›  技术社区  ›  Jesse Orange

使用已验证的数据上载文件

  •  1
  • Jesse Orange  · 技术社区  · 6 年前

    在Laravel中,我有一个简单的函数,它将作业列表存储在数据库中。

    /**
     * Store a new instance of a job posting in the database
     *
     * @param Request $request
     * @return void
     */
    public function store(StoreJobPost $request)
    {
        $job = new JobPost();
    
        $job->position = $request->get('position');
        $job->description = $request->get('description');
        $job->location = $request->get('location');
        $job->business_area = $request->get('business_area');
        $job->contract_type = $request->get('contract_type');
        $job->hours = $request->get('hours');
        $job->salary = $request->get('salary');
        $job->salary_period = $request->get('salary_period');
        $job->attached_description = $request->get('attached_description');
        $job->scheme = $request->get('scheme');
        $job->contact_name = $request->get('contact_name');
        $job->contact_email = $request->get('contact_email');
        $job->contact_number = $request->get('contact_number');
        $job->status = $request->get('status');
        $job->expires_on = $request->get('expires_on');
    
        $job->save();
    
        return redirect()->route('vacancies.index')->with('success', 'Job listing created successfully');
    }
    

    我把它缩短成这样:

    /**
     * Store a new instance of a job posting in the database
     *
     * @param Request $request
     * @return void
     */
    public function store(StoreJobPost $request)
    {
        $validFormData = $request->validated();
    
        $job = JobPost::create($validFormData);
    
        return redirect()->route('vacancies.index')->with('success', 'Job listing created successfully');
    }
    

    但是,我也想存储一个文件。以前我做过这样的事情:

    $file = $request->file('file');
    $path = $file->storeAs('library/', $file->getClientOriginalName());
    

    在这一点上我有:

    $object->path = $path;
    $object->save();
    

    $validatedFormData

    1 回复  |  直到 6 年前
        1
  •  3
  •   Elisha Senoo    6 年前

    当然可以。执行以下操作:

    public function store(StoreJobPost $request)
    {
        $validFormData = $request->validated();
    
        $file = $request->file('file');
        $path = $file->storeAs('library/', $file->getClientOriginalName());
        $validFormData['path']= $path;
    
        $job = JobPost::create($validFormData);
    
        return redirect()->route('vacancies.index')->with('success', 'Job listing created successfully');
    }