0

I have uploaded 15mb image and it throws exception of PostTooLarge Exception instead of exception i have to show flash error message but could not get it.

below is the handler i have used for Handler.php it works great but not display flash message.

if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) 
{
        return redirect()->route('users.add')->withFlashError('Image Size too large!');
}

then i tried validate of laravel for image in my controller which is as below

$validator = Validator::make($request->all(), [
                'image' => 'max:4000',
            ]);
if ($validator->fails()) 
{
        return redirect()->route('user')->withFlashError('Image size exceeds 4MB');                 
}

but still no luck

below is blade file with form:

<form method="post" action="{{route('users.submit')}}" id="adduser" enctype="multipart/form-data">
                            {{csrf_field()}}
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label  class="col-form-label">User name*</label>
                                        <input type="text" class="form-control" name="name" placeholder="User name" value="{{ old('name') }}">
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label  class="col-form-label">User email*</label>
                                        <input type="text" class="form-control" name="email"  value="{{ old('email') }}" placeholder="User email" autocomplete="off">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label  class="col-form-label">Password*</label>
                                        <input id="password" type="password" class="form-control" name="password" placeholder="Password">
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label  class="col-form-label">Confirm password</label>
                                        <input type="password" class="form-control" name="confirmpassword" placeholder="Confirm password">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label  class="col-form-label">Phone number*</label>
                                        <input type="text" class="form-control" name="mobile" value="{{ old('mobile') }}" placeholder="Phone Number">
                                    </div>                              
                                    <div class="col-md-6">
                                        <label  class="col-form-label">User role*</label>
                                        <select name="role" class="form-control valid">
                                            <option   value="">Select Role</option>
                                            <option {{ old('role')==3?'selected':'' }} value="3">Author</option>
                                            <option {{ old('role')==5?'selected':'' }} value="5">Product Admin</option>
                                        </select>
                                    </div>
                                </div>      
                            </div>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="col-md-6">
                                            <label  class="col-form-label">User image</label>
                                            <div class="card-body">
                                                <div class="was-validated">
                                                    <label class="custom-file">
                                                        <input type="file" name="image" accept=".jpg, .png,.jpeg" id="file" class="custom-file-input">
                                                        <span class="custom-file-control"></span>
                                                    </label>
                                                    <ul class="preview" style="margin-top: 10px;"> 

                                                    </ul>
                                                </div>
                                            </div>
                                        </div>                                  
                                </div>
                            </div>  
                            <button style="float: right;" type="submit" class="btn btn-primary" id="validateForm">Save</button>
                        </form>

and below is controller code :

<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Validator;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       $users = User::whereNotIn('role', array(1,4))->orderBy('id','DESC')->get();
       return view('admin.users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.users.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data=$request->all();

        $validate = Validator::make($data, [
            'email' => 'required|string|email|max:255|unique:users',      
        ]);

        if ($validate->fails()) {
            return redirect('users/add')->withFlashError('Email already exists')->withInput();
        }
        if(isset($_FILES['image']))
        {
            $validator = Validator::make($request->all(), [
                'image' => 'max:4000',
            ]);
            if ($validator->fails()) 
            {
                //return redirect()->route('user')->withFlashError('Image size exceeds 4MB'); 
                //return redirect()->route('user')->withErrors(['error' => 'Image size exceeds 4MB']);
                //return redirect('users/add')->withFlashError('Image size exceeds 4MB')->withInput();
                return redirect()->back()->withErrors(['error' => 'Image size exceeds 4MB']);                
            }
            if(basename($_FILES['image']['name']) != "")
            {
                $target_path = base_path().'/public/user/';
                $time=round(microtime(true));
                $newfilename = $target_path .$time . '.jpg'; 
                $target_path = $target_path .time().basename($_FILES['image']['name']);

                if (move_uploaded_file($_FILES['image']['tmp_name'], $newfilename)) 
                {
                    $user_data['image'] =$time.'.jpg';  
                }
            } 
            else
            {
                $user_data['image'] = "";   
            }
        }
        $insert_data = array
                    (
                        "name" => $data['name'],
                        "email" => $data['email'],
                        "password" => bcrypt($data['password']),
                        "mobile" => $data['mobile'],
                        "image" => $user_data['image'],        
                        "role" => $data['role'],
                        "status" => 1
                    );
        User::create($insert_data);
        return redirect()->route('users')->withFlashSuccess('User added successfully');            
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       $user = User::find($id);    
       $user->delete(); 
       return redirect()->route('users')->withFlashSuccess('User deleted successfully');
    }

    public function delete($id)
    {
         $news = User::find($id);    
         $news->delete();      
    }

    public function status($id)
    {
        $store=User::find($id);
        if($store->status==1)
        {
            $status=0;
        }
        else
        {
            $status=1;
        }
        User::whereId($id)->update(array('status'=>$status));
        return redirect()->route('users')->withFlashSuccess('User status changed');
    }

    public function saverole(Request $request)
    { 
        $data=$request->all();
        $string_role = implode(', ', $data['role']);
        User::whereId($data['user_id'])->update(array('role'=>$string_role));
        return redirect()->route('users')->withFlashSuccess('User role changed');
    }
}
raju_odi
  • 1,433
  • 13
  • 29
  • Your handler is correctly capturing the error. You just have to figure out your frontend (blade files). See: https://stackoverflow.com/questions/36784253/laravel-5-2-validation-error-not-appearing-in-blade and follow this tutorial to display flash message: https://itsolutionstuff.com/post/laravel-5-implement-flash-messages-with-exampleexample.html – Mysteryos Jul 16 '18 at 06:08
  • Check your php.ini for post_max_size param. – ipave Jul 16 '18 at 05:51
  • yes i have check and i dont want to make any changes in that instead i want to show flash error if image is more than 4mb in size. – raju_odi Jul 16 '18 at 05:52
  • that is i alredy know about php.ini – raju_odi Jul 16 '18 at 05:53

2 Answers2

0

Change your validate line of code to this:

    $this->validate(request(), [ 
                'image' => 'max:4000'
            ],
[
'image.max' => 'Image size exceeds 4MB'
]);

And inside your view file, run this code to display the errors:

@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif   
Polaris
  • 1,219
  • 8
  • 14
  • added this code still no luck as its routing proper but not displaying flash message – raju_odi Jul 16 '18 at 06:41
  • Try return redirect()->back()->withErrors(['error' => 'Image size exceeds 4MB']); Also edited the answer post with the same code. redirect()->back() will usually store the errors into the session and you should be able to access them with the $errors->first() method in blade. – Polaris Jul 16 '18 at 07:21
  • still no luck as i think its not validating so `if ($validator->fails()) {` that's why not redirecting with flash message – raju_odi Jul 16 '18 at 07:35
  • now its showing exception for `PostTooLargeException`. – raju_odi Jul 16 '18 at 07:36
  • @raju_eww Try it this way, edited my original answer $this->validate(request(), [ 'image' => 'max:4000' ], [ 'image.max' => 'Image size exceeds 4MB' ]); – Polaris Jul 16 '18 at 07:51
  • Okay but what about redirection? and still no luck. – raju_odi Jul 16 '18 at 07:57
  • @raju_eww redirection happens automatically when using the validate() helper method. Post your blade file and post your controller that your form is posting to. This literally makes no sense why this is failing. – Polaris Jul 16 '18 at 07:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176037/discussion-between-raju-eww-and-polaris). – raju_odi Jul 16 '18 at 08:02
-1

Because the php.ini stands first while throwing exception, it will not carry forward that expectation to your defined errors.

Smit Patel
  • 1,682
  • 18
  • 23