ufodisko's avatar

IF statement does not reach the final ELSE condition

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 statement, 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.

0 likes
7 replies
ufodisko's avatar

@tomi I was leaving refactoring till I get the function to work properly.

I tried your snippet, and it's still not displaying the error if I submit an empty status.

dylanh's avatar

If it's not reaching the last else, then it means that its either not getting into the first if statement or it is passing your second or third if statement.

I'd start by figuring out which of the 2 its passing or where its ending up in your code (Do a die-dump or log to a file in each of those statements and see where it's ending up)

Personally, when nothing else is working and I want to get down to basics, I just put a bunch of these all over the script to see where it ends up.

Log::info('Got to line : '__LINE__);
rsands's avatar

Can you post your updated full controller function after @tomi refactor?

andrewclark's avatar

Make use of the ValidatesRequests trait from App\Http\Controllers\Controller to remove a lot of the validation boilerplate. The docs for it are here.

This refactor isn't perfect but its a step in the right direction. I'd look at moving the image handling code else where next!

public function index(Request $request)
{
    /**
     * Ensure that we have a valid status-text and the image
     * is at least a valid MIME-type. If not, they will be
     * redirected back by by the ValidatesRequests trait.
     */
    
    $rules = [
        'status-text' => 'required|string',
        'status_image_upload' => 'mime:jpeg,png'
    ];

    $this->validate($request, $rules);

    /**
     * Create the base status.
     */
    
    $userStatus = new Status;
    $userStatus->status_text = $text;
    $userStatus->user_id = Auth::user()->id;

    /**
     * If there is an image, process it.
     */

    if($request->hasFile('status_image_upload') ) {
        $image = $request->file('status_image_upload');

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

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

        /**
         * Add the image name and type to status.
         */
        $userStatus->image_url = $imageName;
        $userStatus->type = 1;
    }

    /**
     * Save the completed Userstatus model.
     */

    $userStatus->save();
    flash('Your status has been posted', 'success');

    return redirect(route('feed'));
}
ufodisko's avatar

@rsands This is my entire controller with @tomi refactored code. It's still not working, but now I get redirected to a blank page whenever I submit an empty status.

And at the end of each function, the last curly bracket is highlighted in PHPStorm, when I hover over it I get this notice Missing return statement...

I have 4 functions: index(), postStatus(), postComment(), likeStatus() and dislikeStatus()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Status;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class FeedController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function index() {

        return view('home', [
            'top_15_posts' => Status::take(15)->orderBy('created_at', 'desc')->get()
        ]);
    }

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

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

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

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

            $userStatus = new Status;
            $userStatus->status_text = $text;

            if($request->hasFile('status_image_upload'))
            {
                $image = $request->file('status_image_upload');

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

                $image->move('uploads/status_images', $imageName);
                $userStatus->image_url = $imageName;
                $userStatus->type = 1;
            }


            $userStatus->user_id = Auth::user()->id;
            flash('Your status has been posted', 'success');

            return redirect(route('feed'));
        }
    }

    public function likeStatus() {
        if(Input::has('like_status')) {
            $status = Input::get('like_status');
            $selectedStatus = Status::find($status);

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

            return redirect(route('feed'));
        }
    }

    public function dislikeStatus() {
        if(Input::has('dislike_status')) {
            $status = Input::get('dislike_status');
            $selectedStatus = Status::find($status);

            $selectedStatus->likes()->delete();

            return redirect(route('feed'));

        }
    }

    public function postComment(Request $request) {
        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);
            }
        }
    }
}
ufodisko's avatar

It worked, with my original code.

The problem was, I was doing all the posting (post comment, post status, like and dislike) in the same function index - all the if else statements were inside the same function.

Once I broke them into separate functions, everything worked including the validation and error message when submitting an empty status.

I guess I should've done that from the start.

I made some spaghetti code.

ufodisko's avatar

@tomi Your code displays the error message if I submit an empty status, but when I write something, I get the success flash message but my text is not being submitted to the database. I think you missed $userStatus->save()

Please or to participate in this conversation.