Laravel Course

You may access uploaded files using the file() method or using dynamic properties ($request->field_name).
$file = $request->file('photo');
//Or:
$file = $request->photo;

Checking if a file for upload

You may determine if a file is present on the request using the hasFile() method.
In addition to checking if the file is present, you can also check whether the file was successfully received by using the isValid() method
if($request->hasFile('photo') && $request->file('photo')->isValid('photo')){
  //
}

UploadedFile class instance

The file() method returns an instance of the Illuminate\Http\UploadedFile class (which extends the PHP SplFileInfo class), and provides a variety of methods to inspect and interact with the file.
For more information regarding these methods, check out the UploadedFile class methods

- Example, simple Laravel script to upload images, with setings for maximum allowed file size and file extension validation.

1. Create an "uploads" folder in the "public/" directory.
2. Add the following code in a "UploadController.php" file (in app/Http/Controllers/ directory):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UploadController extends Controller {
  protected $exts =['bmp', 'gif', 'jpe', 'jpeg', 'jpg', 'png']; //allowed file exttensions
  protected $max_size =0.5; //allowed maximum file size in MB
  protected $dir ='uploads'; //folder for uploaded files (in public/ directory)
  protected $err =[]; //store errors

  //Responds to post requests to /upload/photo
  //receives the $request instance
  //return string
  public function uploadPhoto(Request $request){
    //if file is sent
    if($request->hasFile('photo')){
      $file = $request->file('photo');

      //if file successfully received
      if($file->isValid()){
        //validate the file
        $ext = $file->guessExtension();
        $size = $file->getClientSize();
        if(!in_array($ext, $this->exts)) $this->err[] ='File extension: '. $ext .'<br>Allowed file exttensions: '. implode(', ', $this->exts);
        if($size >$this->max_size*1024*1024) $this->err[] ='File extension: '. $size .'<br>Allowed maximum file size: '. $this->max_size .' MB';

        //if no error, move the file
        if(count($this->err)==0){
          $fname = $file->getClientOriginalName();
          $fmoved = $file->move(base_path() .'/public/'. $this->dir, $fname);

          //if successfully moved in uploads directory
          if($fmoved){
            return 'File successfully uploaded:<br>'. $this->dir .'/'. $fname .'<br><img src="/'. $this->dir .'/'. $fname .'" alt="Photo" />';
          }
          else $this->err[] ='Unable to move the file to: '. $this->dir .'/'. $fname;
        }
      }
      else $this->err[] ='The file not received';
    }
    else $this->err[] ='No photo file';

    if(count($this->err) >0) return implode('<br>', $this->err);
  }
}
3. Add the following code in a file "upload_form.blade.php" (in the "resources/views/" folder):
<h4>Upload Photo<h4>
<form method="post" action="/upload/photo" enctype="multipart/form-data">
{{ csrf_field() }}
File: <input type='file' name='photo'/><br>
<input type='submit' value='Upload'/>
</form>
4. Add the this code in the "routes/web.php" file:
//shows the upload form
Route::name('upload')->get('/upload', function(){
  return view('upload_form');
});

//when the upload form is submited
Route::post('/upload/photo', 'UploadController@uploadPhoto');
5. Visit the following URL, and select a file for upload:
//localhost:8000/upload
- It will display a page like in this image:
laravel upload form
6. Click Upload button, it will open a page with the uploaded image, as shown in the following image:
laravel uploaded file

Another Upload Image example is to this Page: //coursesweb.net/laravel/validation#anc_pex
- The Upload-form contains Title and Descripton fields, and it uses Laravel validation model.

Another way to save the uploaded files on server is to use the store('folder') or storeAs('folder', 'file_name.ext') method.
These methods store the files in the specified "folder" in the "storage/app" directory.
The store() method automatically generate a unique ID for the file name.
The storeAs() method receives a second argument for the name of the file.
- Example:
//store the uploaded 'photo' file in storage/app/uploads/

//with a unique generated name
$path = $request->photo->store('uploads');
echo $path; // uploads/wAwyYljmEkjHaucksuHM2luPiyUMNApmKrt1L3LK.png

//with the original file name
$fname = $request->photo->getClientOriginalName();
$path = $request->photo->storeAs('uploads', $fname);
echo $path; // uploads/image.png

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Uploaded files

Last accessed pages

  1. Get Attribute (ID, Class, Name, Title, Src) with jQuery (74421)
  2. Add, Change, and Remove Attributes with jQuery (46246)
  3. Read Excel file data in PHP - PhpExcelReader (96690)
  4. Image object (1398)
  5. Animation with the Timer class (1718)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (250)
  2. Read Excel file data in PHP - PhpExcelReader (91)
  3. PHP Unzipper - Extract Zip, Rar Archives (76)
  4. The Four Agreements (75)
  5. The Mastery of Love (66)