【问题标题】:Laravel Contact Form empty attach FileLaravel 联系表格空附加文件
【发布时间】:2018-06-19 21:06:57
【问题描述】:

我是 laravel 的新手, 我正在使用 laravel 5.6 构建一个发送电子邮件的联系表单,其中包含一些字段和文件附件。

表单正在工作,它发送所有字段,但只有当我将附加输入留空时,才会引发错误。

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function isValid() on null

我需要文件字段可以为空
'文件' => '有时'

控制器:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactFormRequest;

class ContactController extends Controller
{
    public function show()
    {
        return view('contact.show');
    }

    public function send(ContactFormRequest $request)
    {
        // upload photo file
        $filePath = $this->upload($request->file('file'));

        $fullName = $request->get('firstname');

        \Mail::send('emails.contact', array(
                'fullName' => $request->get('firstname'),
                'email' => $request->get('email'),
                'body' => $request->get('message'),
                'file' => $filePath,
                'company' =>$request->get('company'),
                'insta' =>$request->get('insta'),
                'web' =>$request->get('web'),
                'description' =>$request->get('description'),
                'phone' =>$request->get('phone'),



            ), function($message) 
            {
                $message->from('my@mail.cl');
                $message->to('my@mail.cl', 'Nombre')->subject('Tienes un nuevo registro de !');
            }
        );

        return \Redirect::route('contact_show', array('locale' => \Lang::getLocale()))
            ->with('message', 'Gracias por inscribirte!\' nos pondremos en contacto contigo lo antes posible!');
    }

    protected function upload($file)
    {
        if ($file->isValid()) {
            $fileName = (new \DateTime())->format('d.m.Y-hsi').'.'.$file->guessExtension();
            $file->move(storage_path() . '/uploads', $fileName);
            return storage_path() . '/uploads/' . $fileName;
        } else {
            return \Redirect::route('contact_show')
                ->with('message', 'El Archivo no es valido!');
        }        
    }
}

请求:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class ContactFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'firstname' => 'required',
            'email' => 'required|email',
            'message' => 'sometimes',
            'company' => 'sometimes',
            'phone' => 'required',
            'insta' => 'sometimes',
            'web' => 'sometimes',
            'description' => 'required',
            'file' => 'sometimes'

        ];
    }
}

表格:

@extends('base')

@section('content')

    @if (Session::has('message'))
        <div class="alert alert-info">
            {{ Session::get('message') }}
        </div>
    @endif

    <h1>{{ trans('contact.contact_us') }}</h1>
    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>

    {!! Form::open(array('route' => 'contact_send', 'class' => 'form', 'files' => true)) !!}

    <div class="form-group">
        {!! Form::label(Lang::get('first name')) !!}
        {!! Form::text('firstname', null, array('required', 'class' => 'form-control')) !!}
    </div>

    <div class="form-group">
        {!! Form::label(Lang::get('Empresa')) !!}
        {!! Form::text('company', null, array('class' => 'form-control')) !!}
    </div>
    <div class="form-group">
        {!! Form::label(Lang::get('insta')) !!}
        {!! Form::text('insta', null, array( 'class' => 'form-control')) !!}
    </div>
        <div class="form-group">
        {!! Form::label(Lang::get('web')) !!}
        {!! Form::text('web', null, array( 'class' => 'form-control')) !!}
    </div>
    <div class="form-group">
        {!! Form::label(Lang::get('email')) !!}
        {!! Form::text('email', null, array('required', 'class' => 'form-control')) !!}
    </div>
    <div class="form-group">
        {!! Form::label(Lang::get('phone')) !!}
        {!! Form::text('phone', null, array('required','class' => 'form-control')) !!}
    </div>
        <div class="form-group">
        {!! Form::label(Lang::get('description')) !!}
        {!! Form::text('description', null, array('required','class' => 'form-control')) !!}
    </div>
    <div class="form-group">
        {!! Form::label(Lang::get('photo')) !!}
        {!! Form::file('file', null, array('class' => 'form-control')) !!}
    </div>

    <div class="form-group">
        {!! Form::label(Lang::get('message')) !!}
        {!! Form::textarea('message', null, array('class' => 'form-control')) !!}
    </div>

    <div class="form-group">
        {!! Form::submit(Lang::get('send'), array('class' => 'btn btn-primary')) !!}
    </div>
    {!! Form::close() !!}

@endsection

【问题讨论】:

    标签: php laravel symfony email contact


    【解决方案1】:

    首先将验证规则从'file' =&gt; 'sometimes'更正为'file' =&gt; 'file',然后在检查$file-&gt;isValid()之前对function upload()进行一点点更改,你必须检查它是空还是空。

    • 要检查它是否为空,请使用is_null($file)
    • 检查变量未设置!isset($file)

    更多详情请点击链接check if variable empty

    【讨论】:

      【解决方案2】:

      您错误地使用了sometimes 验证规则。

      根据文档,如果您想在传递的数组中存在值时应用其他验证规则,则使用该验证规则。

      https://laravel.com/docs/5.6/validation#conditionally-adding-rules

      您的验证数组应如下所示:

      return [
          'firstname' => 'required|string',
          'email' => 'required|email',
          'message' => 'string',
          'company' => 'string',
          'phone' => 'required',
          'insta' => 'string',
          'web' => 'url',
          'description' => 'required|string',
          'file' => 'file'
      ];
      

      另外我建议您不要使用表单生成器。尽管它仍在 Laravel 中,但它已经从 laravel 文档中删除了一段时间,但构建 html 也同样简单。

      我不确定这是否会直接解决您的问题,但希望它会是相关的:)。

      【讨论】:

      • 感谢您的回答!这并不能解决错误,但谢谢我尝试不要使用表单生成器
      • 不用担心,如果这回答了您的问题,请将答案标记为正确答案:)。
      【解决方案3】:

      如果表单文件为空,我修复了发送默认 img 的问题

      我的控制器

          public function upload($file)
          {
          if (is_null($file)) {
      
           return storage_path() . '/uploads/' . '1.png';
      
         }   
         else {
                     if ($file->isValid()) {
                  $fileName = (new \DateTime())->format('d.m.Y-hsi').'.'.$file->guessExtension();
                  $file->move(storage_path() . '/uploads', $fileName);
                  return storage_path() . '/uploads/' . $fileName;
              } else {
                  return \Redirect::route('contact_show')
                      ->with('message', 'El Archivo no es valido!');
              }     
         }   
          }
      

      我的请求

          return [
      'firstname' => 'required',
      'email' => 'required|email',
      'message' => 'nullable',
      'company' => 'nullable',
      'phone' => 'required',
      'insta' => 'nullable',
      'web' => 'nullable',
      'description' => 'required',
      'file' => 'mimes:jpeg,bmp,png,mp4s,doc,dot,pdf,docx,cgm,gif,jpg,jpe,svg,txt,mp4,mov',
      
          ];
      

      mimes 是为我的文件上传工作的验证

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 2017-10-11
        • 2016-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多