1

I have been trying to validate input fields on a project I'm working on. It has not been returning the validation errors. Also each time I remove the validation and I attempt to submit the form data after filling it, it returns an undefined index error.

This is my Controller


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\staffLogin;
use Validator;
use App\Country;
use App\Category;
use App\User;
use App\Resume;
use Image;
use Auth;
use Session; 
use DB;


class EnrolController extends Controller
{
    public function home(){
        $title = 'home';

        return view('staff.home');
    }

    public function profile(Request $request){
        $title ='profile';

        $user_id = Auth::user()->id;
        $user_name = Auth::user()->name;
        $user_email = Auth::user()->email;
        $userDetails = User::find($user_id);

        if($request->isMethod('post')){
            $data = $request->all();
            // echo "<pre>"; print_r($data); die;
            $data = request()->validate([
                'category_id' => 'required',
                // 'firstname' => 'required|regex:/^[\pL\s\-]+$/u|max:255',
                // 'lastname' => 'required|regex:/^[\pL\s\-]+$/u|max:255',
                'age' => 'required',
                'phone' => 'required',
                'gender' => 'required',
                'address' => 'required',
                'country' => 'required',
                'image' => 'required',
                'cv' => 'required',
                'experience' => 'required',
                'education' => 'required',
                'salary' => 'required',
                'employment_type' => 'required',
                'summary' => 'required',
            ]);

                $resume = new Resume;
                $resume->user_id = $user_id;
                $resume->user_name = $user_name;
                $resume->user_email = $user_email;
                $resume->category_id = $data['category_id'];
                $resume->age = $data['age'];
                $resume->gender = $data['gender'];
                $resume->address = $data['address'];
                $resume->country = $data['country'];
                $resume->phone = $data['phone'];
                // $resume->image = $data['image']->store('uploads/passport');
                // $resume->image = $data['cv']->store('uploads/cv');

                    // Upload Passport
                    if($request->hasFile('image')){
                        $image_tmp = $request->image;
                        if ($image_tmp->isValid()) {
                            // Upload Images after Resize
                            $extension = $image_tmp->getClientOriginalExtension();
                            $fileName = rand(111,99999).'.'.$extension;
                            $large_image_path = 'images/uploads/passport/large'.'/'.$fileName;
                            $medium_image_path = 'images/uploads/passport/medium'.'/'.$fileName;
                            $small_image_path = 'images/uploads/passport/small'.'/'.$fileName;

                            Image::make($image_tmp)->save($large_image_path);
                            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
                            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);

                            $resume->image = $fileName; 

                        }
                    }  

                    // Upload CV
                    if($request->hasFile('cv')){
                        $image_tmp = $request->cv;
                        if ($image_tmp->isValid()) {
                            // Upload Images after Resize
                            $extension = $image_tmp->getClientOriginalExtension();
                            $fileName = rand(111,99999).'.'.$extension;
                            $large_image_path = 'images/uploads/cv/large'.'/'.$fileName;
                            $medium_image_path = 'images/uploads/cv/medium'.'/'.$fileName;
                            $small_image_path = 'images/uploads/cv/small'.'/'.$fileName;

                            Image::make($image_tmp)->save($large_image_path);
                            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
                            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);

                            $resume->cv = $fileName; 

                        }
                    }  

                $resume->education = $data['education'];
                $resume->experience = $data['experience'];
                // $resume->salary = $data['salary'];
                if(!empty($data['salary'])){
                    $resume->salary = $data['salary'];
                }else{
                    $resume->salary = ''; 
                }
                $resume->employment_type = $data['employment_type'];
                $resume->verification = $data['verification'];
                // if(empty($data['verification'])){
                //     $verification='0';
                // }else{
                //     $verification='1';
                // }
                $resume->summary = $data['summary'];
                // if(!empty($data['summary'])){
                //     $resume->summary = $data['summary'];
                // }else{
                //     $resume->summary = ''; 
                // }
                $resume->status = $data['status'];
                // if(empty($data['status'])){
                //     $status='0';
                // }else{
                //     $status='1';
                // }
                // $resume->save();

                return redirect()->back()->with('flash_message_success', 'Resume Added!!!');
            }


        // if($request->isMethod('post')){
        //  $data = $request->all();
            // echo "<pre>"; print_r($data); die;

        $countries = Country::get();

        $categories = Category::where(['parent_id' => 0])->get();

        $categories_drop_down = "<option value='' selected disabled>Select</option>";
        foreach($categories as $cat){
            $categories_drop_down .= "<option value='".$cat->id."'>".$cat->name."</option>";
            $sub_categories = Category::where(['parent_id' => $cat->id])->get();
            foreach($sub_categories as $sub_cat){
                $categories_drop_down .= "<option value='".$sub_cat->id."'>&nbsp;&nbsp;--&nbsp;".$sub_cat->name."</option>";    
            }
        }



        return view('staff.add_profile')->with(compact('staffDetails', 'categories_drop_down', 'countries'));
    }

    public function viewProfile() {

        $resume = Resume::get();

        return view('staff.view_profile')->with(compact('resume'));
    }

}

This is my form


@section('content')

    <div class="section wb">
        <div class="container">

            @if(Session::has('flash_message_success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button> 
                        <strong>{!! session('flash_message_success') !!}</strong>
                </div>
            @endif
            @if(Session::has('flash_message_error'))
                <div class="alert alert-error alert-block" style="background-color:#f4d2d2">
                    <button type="button" class="close" data-dismiss="alert">×</button> 
                        <strong>{!! session('flash_message_error') !!}</strong>
                </div>
            @endif  

            <div class="section-title text-center">
                <h3>My Profile {{ Auth::user()->name }}</h3>
            </div><!-- end title -->

        <form enctype="multipart/form-data" name="addprofile" id="addprofile" method="post" action="{{ url('/add-resume') }}">{{ csrf_field()}}

        <div class="form-group">
            <label for="category_id">Category</label>
            <select class="form-control" id="category_id" name="category_id">
            <option value="">Select Category</option>
                <?php echo $categories_drop_down; ?>
            </select>
        </div>

        <div class="form-group">
            <label for="age">Age</label>
            <input type="text" class="form-control" name="age" id="age" placeholder="Age" >
        </div>

        <div class="form-group">
            <label for="gender">Gender</label>
            <select class="form-control" id="gender" name="gender" >
                <option value="not specified">Select Gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select>
        </div>

        <div class="form-group">
            <label for="address">Address</label>
            <textarea class="form-control" name="address" id="address" rows="3" ></textarea>
        </div>

        <div class="form-group">
            <label for="country">Country</label>
            <select class="form-control" id="country" name="country" >
            <option value="">Select Country</option>
                @foreach($countries as $country)
                <option value="{{ $country->country_name }}">{{ $country->country_name }}</option>
                @endforeach
            </select>
        </div>

        <div class="form-group">
            <label for="phone">Phone</label>
            <input type="phone" class="form-control" name="phone" id="phone" placeholder="Phone" >
        </div>

        <div class="form-group">
            <label for="education">Education Level</label>
            <select name="education" class="form-control" >
                  <option value="" selected disable>Select Education Level</option>
                  <option value="High School/Secondary School">High School/Secondary School</option>
                  <option value="Diploma">Diploma</option>
                  <option value="Bachelors' Degree">Bachelors' Degree</option>
                  <option value="Masters">Masters</option>
                  <option value="Doctorate">PhD</option>
            </select>
        </div>

        <div class="form-group">
            <label for="experience">Experience</label>
            <textarea type="text" class="form-control" rows="3" name="experience" id="experience" placeholder="Experience" ></textarea>
        </div>

        <div class="form-group">
            <label for="salary">Salary</label>
            <input type="phone" class="form-control" name="salary" id="salary" placeholder="Expected Base Salary" >
        </div>

        <div class="form-group">
            <label for="employment_type">Employment Type</label>
            <select name="employment_type" class="form-control" >
                  <option value="" selected disable>Select Employment Type</option>
                  <option value="Any">Any</option>
                  <option value="Part Time">Part Time</option>
                  <option value="Full Time">Full Time</option>
                  <option value="Freelance">Freelance</option>
            </select>
        </div>

        <div class="form-group">
            <label for="image">Passport (*jpg, *png, *jpeg)</label>
            <input type="file" name="image" class="form-control-file" id="image" >
        </div>

        <div class="form-group">
            <label for="cv">A Page CV (*jpg, *png, *jpeg)</label>
            <input type="file" name="cv" class="form-control-file" id="cv" >
        </div>

        <div class="form-group">
            <label for="summary">Summary</label>
            <textarea type="text" class="form-control" rows="3" name="summary" id="summary" placeholder="Summary" ></textarea>
        </div>

        <div class="form-group">
        <button type="submit" class="btn btn-primary">Submit</button>
        </div>
        </form>


 </div>
</div>

@endsection

This is my route web.php


// use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

    // Route::get('/', function () {
    //     return view('index');
    // });


    Route::get('/', 'frontController@index');

    Route::get('/home', 'EnrolController@home');


    Route::match(['get', 'post'], '/admin', 'AdminController@login');

    Route::match(['get', 'post'], '/about', 'frontController@about');

    Route::match(['get', 'post'], '/contact', 'frontController@contact');

    // Users Login/Register Page
    Route::get('/login-register','UsersController@userLoginRegister');

    // Staff Register Page
    Route::match(['get', 'post'], '/staff-register','StaffController@register');

    Route::match(['get','post'],'/forgot-password','UsersController@forgotPassword');

    Route::get('/resume/{url}','ResumeController@resumes');

    // Resume Detail Page
    Route::get('/resume/{id}','ResumeController@resume');

    // Users Register Form Submit
    Route::post('/user-register','UsersController@register');

    // Confirm Account
    Route::get('confirm/{code}','UsersController@confirmAccount');

     // Confirm Account
     Route::get('home/confirm/{code}','StaffController@confirmAccount');

    // Users Login Form Submit
    Route::post('/user-login','UsersController@login');

    // Staff Login Form Submit
    Route::post('/staff-login','StaffController@login');

    // Staff forgot password
    Route::match(['get','post'],'/staff-forgot-password','StaffController@forgotPassword');

    // Staff logout
    Route::get('/staff-logout','StaffController@logout');

    // Users logout
    Route::get('/user-logout','UsersController@logout');

    Route::match(['get','post'],'/staff-forgot-password','StaffController@forgotPassword');


    Route::group(['middleware' => ['stafflogin']], function () {
        Route::get('/staff/dashboard', 'StaffController@dashboard');
        Route::get('/staff/settings','StaffController@settings');
        Route::get('/staff/check-pwd','StaffController@chkPassword');
        Route::match(['get', 'post'],'/staff/update-pwd','StaffController@updatePassword');

        Route::match(['get', 'post'],'/add-profile','EnrolController@profile');
        Route::match(['get', 'post'],'/view-profile','EnrolController@viewProfile');

        Route::match(['get','post'],'/add-resume','EnrolController@profile');
        Route::get('/admin/view-profile','ResumeController@viewProfile');
        Route::match(['get', 'post'], '/admin/edit-resume/{id}','ResumeController@editResume');        

    });






1 Answer 1

3

Try the following

use use Illuminate\Support\Facades\Validator;
//...
$validator = Validator::make($request->all(), [
     'category_id' => 'required',
     ...
]);

if ($validator->fails()) {
     return redirect()->back()
         ->withErrors($validator)
         ->withInput();
}

$data = $validator->validated();
Sign up to request clarification or add additional context in comments.

7 Comments

I tried doing it that way but it returns a Type error. TypeError Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in C:\wamp64\www\virtual\app\Http\Controllers\EnrolController.php on line 41
I also tried using $data = request()->validate([ ]); which worked before but still no luck
Did you tried the Validator facade ? if not check my updated answer
ErrorException Undefined index: category_id came up on using the updated answer with the Validator facade
I missed this instruction $data = $validator->validated(); . Hope it solves the issue
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.