简体   繁体   中英

Laravel 5 if condition not working on last condition (else)

I have a text field status-text that allows users to submit their statuses.

I also have an image upload field to add a picture to the status.

In my if condition, I am checking first to see if the input has any data, then I check if the input has an image AND validator doesn't fail, then I check if validator doesn't fail (to submit a status without an image), at the end I do an else which is supposed to be "if input doesn't have any data"

The first 3 checks are working but the last else is not. Apparently the code is not reaching that final else for some reason.

This is the view

@if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
@endif
@include('partials/flash')
<div class="row">
        <div class="col-md-12">
            {!! Form::open(['files' => true]) !!}
            <div class="panel panel-default">
                <div class="panel-heading">Add New Status</div>

                <div class="panel-body">
                    <div class="form-group">
                        <label for="status-text">Write Something</label>
                        <textarea class="form-control" name="status-text" id="status-text"></textarea>
                    </div>
                </div>

                <div class="panel-footer clearfix">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="file-upload" class="custom-file-upload">
                                <i class="fa fa-image"></i>
                            </label>
                            <input id="file-upload" name="status_image_upload" type="file">
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-info btn-sm pull-right"><i class="fa fa-plus"></i> Add Status</button>
                        </div>
                    </div>
                </div>
    </div>
    {!! Form::close() !!}

And this is FeedController@index

if($request->has('status-text')) {
        $text = Input::get('status-text');

        $rules = [
            'status-text' => 'required|string'
        ];

        $validator = Validator::make($request->all(), $rules);

        if($request->hasFile('status_image_upload') && !$validator->fails()) {
            $image = $request->file('status_image_upload');

            $imageName = str_random(8) . '_' . $image->getClientOriginalName();
            //$imageFull = str_random(8) . '_' . $image->getClientOriginalName();

            $image->move('uploads/status_images', $imageName);

            $userStatus = new Status;
            $userStatus->status_text = $text;
            $userStatus->image_url = $imageName;
            $userStatus->type = 1;
            $userStatus->user_id = Auth::user()->id;
            $userStatus->save();
            flash('Your status has been posted');

            return redirect(route('feed'));
        } elseif(!$validator->fails()) {
            $userStatus = new Status;
            $userStatus->status_text = $text;
            $userStatus->user_id = Auth::user()->id;
            $userStatus->save();
            flash('Your status has been posted', 'success');

            return redirect(route('feed'));
        } else {
            $messages = $validator->errors();
            return redirect(route('feed'))->withErrors($messages);
        }

I have tried using if($validator->fails()) - it didn't work. I have also tried returning a simple string return 'field cannot be empty'; just to test it out, it doesn't work either.

I have the same code running for post_comment and it works for the else , so if I leave the comment field empty and submit it, I get redirected to the feed page with an error message saying the field cannot be empty.

THIS WORKS

if(Input::has('post_comment')) {
        $rules = [
            'comment-text' => 'required|string'
        ];

        $validator = Validator::make($request->all(), $rules);

        if(!$validator->fails()) {
            $status = Input::get('post_comment');
            $commentBox = Input::get('comment-text');
            $selectedStatus = Status::find($status);

            $selectedStatus->comments()->create([
                'comment_text' => $commentBox,
                'user_id' => Auth::user()->id,
                'status_id' => $status
            ]);

            flash('Your comment has been posted', 'success');

            return redirect(route('feed'));
        } else {
            $messages = $validator->errors();
            return redirect(route('feed'))->withErrors($messages);
        }
    }

I am not sure what else to try.

In pseudo-code, you say you're trying to do this

if input exists
  if image exists and validator passes

  elsif validator passes

  end
else 
  // no data
end

but your code says you're doing this

if input exists
  if image exists and validator passes

  elsif validator passes

  else 
    // no data
  end
end

I would refactor this entirely. Program defensively.

if no data
  // handle no data
  return;
end

if validator fails
  // handle invalid data
  return;
end

create new Status

if image exists
  // handle image upload
end

flash message
redirect

If you do this you'll remove the duplication with your validation checks, creating a Status, flashing a message, and redirecting.

Try to avoid nesting conditionals. Try to avoid else and else if statements. Your code will be cleaner and more readable as a result.

如果您的文本字段在提交时为空,则不会提出要求。

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