Create Migration Table
Using Migration File in Laravel php artisan make:migration create_uploads_table --create=uploads
Now, open the file database/migrations/{{datetime}}_create_uploads_table.php We will add below code inside the up() method.
Schema::create('uploads', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('group_id');
$table->string('filename');
$table->string('extension');
$table->string('filesize');
$table->string('location');
$table->timestamps();
});
Now open command line and run below command php artisan migrate
Model File into Laravel We will create FileUpload.php into Models/ folder the file location would be app/Models/FileUpload.php. Open file and add below code into this file.
//Models/FileUpload.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FileUpload extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'group_id', 'filename', 'extension', 'filesize', 'location'
];
}
Create Routes and view file into Laravel
We will create view file to display upload form into laravel. We will use session to display upload success and error message.
We will create UploadContactsController.php file and define upload-file method. //App\Http\Controllers\Backend\UploadContactController.php
<?php
namespace App\Http\Controllers\Backend;
use App\Http\Requests\Backend\Contacts\UploadContactsRequest;
use App\Http\Controllers\Controller;
use App\Jobs\UploadContacts;
use App\Models\FileUpload;
use App\Models\Group;
use Session;
class UploadContactsController extends Controller
{
/**
* Upload the contacts file
*
* @param App\Http\Requests\Backend\Contacts\UploadContactsRequest $request
* @param App\Models\Group $group
* @return \Illuminate\Http\Response
*/
public function __invoke(UploadContactsRequest $request, Group $group)
{
if ($request->file('filename')->isValid()) {
$fileUpload = new FileUpload;
$fileUpload->user_id = auth()->user()->id;
$fileUpload->group_id = $group->id;
$fileUpload->filename = $request->file('filename')->hashName();
$fileUpload->extension = $request->file('filename')->extension();
$fileUpload->filesize = $request->file('filename')->getClientSize();
$fileUpload->location = $request->file('filename')->store('contact-files');
$fileUpload->save();
toastr()->success('Data has been saved successfully!');
flash()->success('Your file is currently being processed. You will be notified when done.');
//UploadContacts::dispatch($fileUpload, $group)->onQueue('file-uploads');
dispatch(new UploadContacts($fileUpload, $group))->onQueue('file-uploads');
} else {
flash()->error('There was a problem uploading your file. Please try again.');
}
return back();
}
}
By:Xtreem Solution
If you prefer learning by watching here is simple tutorial : File Upload in Laravel
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community