如何使“上传文件”不是必需的 - Laravel 8

Posted

技术标签:

【中文标题】如何使“上传文件”不是必需的 - Laravel 8【英文标题】:How to make "upload file" optional not required - Laravel 8 【发布时间】:2021-08-19 08:37:37 【问题描述】:

我试图让用户选择是否要上传文件

这是完整的控制器代码:

<?php

namespace App\Actions\Fortify;

use App\Models\Team;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers

use PasswordValidationRules;

/**
 * Create a newly registered user.
 *
 * @param  array  $input
 * @return \App\Models\User
 */
public function create(array $input)



    
    Validator::make($input, [
        'name' => ['required', 'string', 'max:255'],
        'usertype' => ['required', 'string', 'max:255'],
        'firmtype4' => ['required', 'string', 'max:255'],
        'firmName' => ['required', 'string', 'max:255'],
        'comNum' => ['nullable', 'string', 'max:255'],
        'litNote' => ['required', 'string', 'max:255'],
        'linktocomp' => ['required', 'string', 'max:255'],
        'Location' => ['required', 'string', 'max:255'],
        'sex' => ['required', 'string', 'max:255'],
        'BD' => ['required', 'string', 'max:255'],
        'idnumb' => ['required', 'string', 'max:255'],
        'study' => ['required', 'string', 'max:255'],
        'workplace' => ['required', 'string', 'max:255'],
        'whatworkbefore' => ['nullable', 'string', 'max:255'],
        'Soicalmide' => ['required', 'string', 'max:255'],
        'kindofparti' => ['required', 'string', 'max:255'],
        'whyparti1' => ['required', 'string', 'max:255'],
        'prevparti2' => ['nullable', 'string', 'max:255'],
        'whyparti' => ['required', 'string', 'max:255'],
        'smalword' => ['required', 'string', 'max:255'],
        'videolink' => ['nullable', 'string', 'max:255'],
        'applybefore' => ['required', 'string', 'max:255'],
        'howyouknow' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => $this->passwordRules(),
        'fathername' => ['required', 'string', 'max:255'],
        'surname' => ['required', 'string', 'max:255'],
        'phone' => ['required', 'string', 'max:255'],
        'instagram' => ['nullable', 'string', 'max:255'],
        'twitter' => ['nullable', 'string', 'max:255'],
        'linkedin' => ['nullable', 'string', 'max:255'],
    ])->validate();


   

    return DB::transaction(function () use ($input) 

    $request = request();
 if ($request->hasFile('uploadfile')) 
 $profileImage = $request->file('uploadfile');
    $profileImageSaveAsName = time() . "aa" . "-profile." . $profileImage->getClientOriginalExtension();

    
    $upload_path = 'uploads/form1/';
    $profile_image_url = $upload_path . $profileImageSaveAsName;
    $success = $profileImage->move($upload_path, $profileImageSaveAsName);



$request2 = request();
 if ($request2->hasFile('uploadfile2')) 
 $profileImage2 = $request2->file('uploadfile2');
    $profileImageSaveAsName2 = time() . "bb" . "-profile." . $profileImage2->getClientOriginalExtension();

    
    $upload_path2 = 'uploads/form1/';
    $profile_image_url2 = $upload_path2 . $profileImageSaveAsName2;
    $success = $profileImage2->move($upload_path2, $profileImageSaveAsName2);

    


$request3 = request();
 if ($request3->hasFile('uploadfile3')) 
 $profileImage3 = $request3->file('uploadfile3');
    $profileImageSaveAsName3 = time() . "cc" . "-profile." . $profileImage3->getClientOriginalExtension();

    
    $upload_path3 = 'uploads/form1/';
    $profile_image_url3 = $upload_path3 . $profileImageSaveAsName3;
    $success = $profileImage3->move($upload_path3, $profileImageSaveAsName3);



$request4 = request();
 if ($request4->hasFile('uploadfile4')) 
 $profileImage4 = $request4->file('uploadfile4');
    $profileImageSaveAsName4 = time() . "dd" . "-profile." . $profileImage4->getClientOriginalExtension();

    
    $upload_path4 = 'uploads/form1/';
    $profile_image_url4 = $upload_path4 . $profileImageSaveAsName4;
    $success = $profileImage4->move($upload_path4, $profileImageSaveAsName4);





        return tap(User::create([
            'name' => $input['name'],
            'usertype' => $input['usertype'],
            'firmtype4' => $input['firmtype4'],
            'Location' => $input['Location'],
            'firmName' => $input['firmName'],
            'comNum' => $input['comNum'],
            'litNote' => $input['litNote'],
            'linktocomp' => $input['linktocomp'],
            'sex' => $input['sex'],
            'BD' => $input['BD'],
            'idnumb' => $input['idnumb'],
            'study' => $input['study'],
            'workplace' => $input['workplace'],
            'whatworkbefore' => $input['whatworkbefore'],
            'Soicalmide' => $input['Soicalmide'],
            'kindofparti' => $input['kindofparti'],
            'whyparti1' => $input['whyparti1'],
            'prevparti2' => $input['prevparti2'],
            'whyparti' => $input['whyparti'],
            'smalword' => $input['smalword'],
            'partifile' => $profile_image_url,
            'videolink' => $input['videolink'],
            'resume' => $profile_image_url4,
            'previswork' => $profile_image_url3,
            'applybefore' => $input['applybefore'],
            'comprofile' => $profile_image_url4,
            'howyouknow' => $input['howyouknow'],
            'extrapdf' => $profile_image_url2,
            'fathername' => $input['fathername'],
            'surname' => $input['surname'],
            'phone' => $input['phone'],
            'instagram' => $input['instagram'],
            'twitter' => $input['twitter'],
            'linkedin' => $input['linkedin'],
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
        ]), function (User $user) 
            $this->createTeam($user);
        );
    );


/**
 * Create a personal team for the user.
 *
 * @param  \App\Models\User  $user
 * @return void
 */
protected function createTeam(User $user)

    $user->ownedTeams()->save(Team::forceCreate([
        'user_id' => $user->id,
        'name' => explode(' ', $user->name, 2)[0]."'s Team",
        'personal_team' => true,
    ]));


我怎样才能使它可以为空?

我已更新问题以包含控制器的完整代码

现在我面对的是“未定义的变量:profile_image_url”

在我按照答案后,我得到了这个错误

【问题讨论】:

使验证规则可以为空,并使用条件来检查请求是否有文件。 制作一个简单的函数来上传文件然后使用它,检查我的回答我希望它对你有用.. 【参考方案1】:

您可以使用hasFile查看

$request = request();
     if ($request->hasFile('uploadfile')) 
     $profileImage = $request->file('uploadfile');
        $profileImageSaveAsName = time() . "aa" . "-profile." . $profileImage->getClientOriginalExtension();
    
        
        $upload_path = 'uploads/form1/';
        $profile_image_url = $upload_path . $profileImageSaveAsName;
        $success = $profileImage->move($upload_path, $profileImageSaveAsName);
    

参考:https://laravel.com/docs/8.x/requests#retrieving-uploaded-files

更新

根据您的代码,您需要传递 $request

return DB::transaction(function () use ($input) 

 if (\request()->hasFile('uploadfile')) 
 $profileImage = \request()->file('uploadfile');
    $profileImageSaveAsName = time() . "aa" . "-profile." . $profileImage->getClientOriginalExtension();

    
    $upload_path = 'uploads/form1/';
    $profile_image_url = $upload_path . $profileImageSaveAsName;
    $success = $profileImage->move($upload_path, $profileImageSaveAsName);




 if (\request()->hasFile('uploadfile2')) 
 $profileImage2 = \request()->file('uploadfile2');
    $profileImageSaveAsName2 = time() . "bb" . "-profile." . $profileImage2->getClientOriginalExtension();

    
    $upload_path2 = 'uploads/form1/';
    $profile_image_url2 = $upload_path2 . $profileImageSaveAsName2;
    $success = $profileImage2->move($upload_path2, $profileImageSaveAsName2);

    


 if (\request()->hasFile('uploadfile3')) 
 $profileImage3 = \request()->file('uploadfile3');
    $profileImageSaveAsName3 = time() . "cc" . "-profile." . $profileImage3->getClientOriginalExtension();

    
    $upload_path3 = 'uploads/form1/';
    $profile_image_url3 = $upload_path3 . $profileImageSaveAsName3;
    $success = $profileImage3->move($upload_path3, $profileImageSaveAsName3);




 if (\request()->hasFile('uploadfile4')) 
 $profileImage4 = \request()->file('uploadfile4');
    $profileImageSaveAsName4 = time() . "dd" . "-profile." . $profileImage4->getClientOriginalExtension();

    
    $upload_path4 = 'uploads/form1/';
    $profile_image_url4 = $upload_path4 . $profileImageSaveAsName4;
    $success = $profileImage4->move($upload_path4, $profileImageSaveAsName4);

【讨论】:

在我做了你提到的之后,我得到了一个错误“未定义的变量:请求” return DB::transaction(function () use ($input,$request) 在我用你的答案更新代码后,我仍然收到“未定义的变量:请求” 删除请求并在您使用 $request 的任何地方更改为 $input 更新答案。如果您遇到错误请告诉我【参考方案2】:
$input = Request::all();
    $rules = array(
        'name' => 'required|string|max:255',
        'usertype' => 'required|string|max:255'
    );
    $validation = Validator::make($input, $rules, array());
    if ($validation->fails()) 
        $message = $validation->messages()->first();
        return Response()->json(ResponseManager::getError(null, 1, $message));
    
    DB::beginTransaction();
    try 
        $input['uploadfile1'] = null;
        $input['uploadfile2'] = null;
        $input['uploadfile3'] = null;
        $input['uploadfile4'] = null;
        if (Request::hasFile('uploadfile')) 
            $input['uploadfile1'] = $this->upload_file($input['uploadfile'], 'uploads/form1');
        
        if (Request::hasFile('uploadfile2')) 
            $input['uploadfile2'] = $this->upload_file($input['uploadfile2'], 'uploads/form1');
        
        if (Request::hasFile('uploadfile3')) 
            $input['uploadfile3'] = $this->upload_file($input['uploadfile3'], 'uploads/form1');
        
        if (Request::hasFile('uploadfile4')) 
            $input['uploadfile3'] = $this->upload_file($input['uploadfile4'], 'uploads/form1');
        
        $result = User::create($input);
        DB::commit();
        $message = 'success';
        return Response()->json(ResponseManager::getResult(null, 10, $message));
     catch (Exception $e) 
        DB::rollBack();
        $message = $e->getMessage();
        return Response()->json(ResponseManager::getError(null, 8, $message));
    

简单制作一个上传文件的通用函数。

public static function upload_file($image, $store_path) 
    $name = md5(uniqid(rand(), true)) . str_replace(' ', '-', $image->getClientOriginalName());
    $image->move(public_path('/' . $store_path), $name);
    return $store_path . '/' . $name;

希望对你有用

【讨论】:

以上是关于如何使“上传文件”不是必需的 - Laravel 8的主要内容,如果未能解决你的问题,请参考以下文章

Laravel/Blade 表单添加“必需”以选择元素

Laravel 验证 - 数组字段,仅允许两个字段之一,但都不是必需的

Laravel 5.3,检查上传的文件是不是大于upload_max_filesize(可选上传)

Laravel 5.2:测试上传的文件是不是有效:非对象上的 isValid()

如何使代客指向 localhost:8000 而不是 laravel 框架的 htdocs

Laravel 8:如何使隐式模型绑定路由参数可选而不是抛出 404?