Validating and processing the form

In this section, we are going to validate the submitted form and make sure that the required fields are present and the submitted file is an image. Then we will upload the image to our server, process the image, create the thumbnail, and save the image information to the database as follows:

  1. First, we need to define the form validation rules. We prefer adding such values to the related model, so the rules become reusable, and this prevents the code from becoming bloated. To do this, add the following code in the image.php file in the app/models/ directory (the model that we generated earlier in this tutorial) inside the class definition before the last curly bracket(}):
    //rules of the image upload form
    public static $upload_rules = array(
      'title'=> 'required|min:3',
      'image'=> 'required|image'
    );

    We set the variable as public, so it can be used outside the model file, and we set it to static, so we can directly access the variable.

    We want both title and image to be mandatory, and title should have at least three characters. Also, we want to check MIME types of the image column and make sure that it’s an image.

    Note

    Laravel’s MIME-type checking requires the Fileinfo extension to be installed. So make sure it’s enabled in your PHP configuration.

  2. Now we need the controller’s post method to process the form. Add this method in the imageController.php file in app/http/controllers/ before the last curly bracket(}):
    public function postIndex()
    {
      
      //Let's validate the form first with the rules which areset at the model
      $validation = Validator::make(Input::all(),image::$upload_rules);
    
      //If the validation fails, we redirect the user to theindex page, with the error messages 
      if($validation->fails()) {
        return Redirect::to('/')->withInput()->withErrors($validation);
      }
      else {
    
        //If the validation passes, we upload the image to thedatabase and process it
        $image = Input::file('image');
    
        //This is the original uploaded client name of theimage
        $filename = $image->getClientOriginalName();
        //Because Symfony API does not provide filename//without extension, we will be using raw PHP here
        $filename = pathinfo($filename, PATHINFO_FILENAME);
    
        //We should salt and make an url-friendly version of//the filename
        //(In ideal application, you should check the filename//to be unique)
        $fullname = Str::slug(Str::random(8).$filename).'.'.$image->getClientOriginalExtension();
    
        //We upload the image first to the upload folder, thenget make a thumbnail from the uploaded image
        $upload = $image->move(Config::get( 'image.upload_folder'),$fullname);
    
        //Our model that we've created is named image, thislibrary has an alias named image, don't mix them two!
        //These parameters are related to the image processingclass that we've included, not really related toLaravel
        image::make(Config::get( 'image.upload_folder').'/'.$fullname)->resize(Config::get( 'image.thumb_width'),null, true)->save(Config::get( 'image.thumb_folder').'/'.$fullname);
    
        //If the file is now uploaded, we show an error messageto the user, else we add a new column to the databaseand show the success message
        if($upload) {
    
          //image is now uploaded, we first need to add columnto the database
          $insert_id = DB::table('images')->insertGetId(
            array(
              'title' => Input::get('title'),
              'image' => $fullname
            )
          );
    
          //Now we redirect to the image's permalink
          return Redirect::to(URL::to('snatch/'.$insert_id))->with('success','Your image is uploadedsuccessfully!');
        } else {
          //image cannot be uploaded
          return Redirect::to('/')->withInput()->with('error','Sorry, the image could not beuploaded, please try again later');
        }
      }
    }

    Let’s dig the code one by one.

    1. First, we made a form validation and called our validation rules from the model that we’ve generated via image::$upload_rules.
    2. Then we’ve salted (added additional random characters for security) the filename and made the filename URL-friendly. First, we get the uploaded filename with the getClientOriginalName() method, then get the extension with the getClientOriginalExtension() method. We salted the filename with an eight character-long random string, which we gained by the random() method of the STR class. Lastly, we made the filename URL-friendly with Laravel’s built-in slug() method of the STR class.
    3. After all the variables are ready, we first uploaded the file to the server with the move() method, which takes two parameters. The first parameter is the path to which the file is going to be transferred, the second parameter is the filename of the uploaded file.
    4. After uploading, we created a static thumbnail for the uploaded image. For this, we benefited from Intervention, an image processing class we’ve implemented earlier.
    5. Lastly, if everything goes okay, we add the title and image filenames to the database and get the ID with the insertGetId() method of Fluent Query Builder, which inserts the row first and returns insert_id of the column. We could also create the row with Eloquent ORM by setting the create() method to a variable and get the id_column name such as $create->id.
    6. After everything is okay and we get insert_id, we redirect the user to a new page that will show thumbnails, full-image links, and a forum thumbnail BBCode, which we will generate in the next sections.