Laravel Backpack file upload - laravel

I recently installed laravel backpack
And my form has a pdf file to upload
I read the tutorial on backpack but was unable to solve it
I Debugged and found that
request()->hasFile() is empty
no file in request
and html code of the add form has no enctype="" in it

routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;
/*
|--------------------------------------------------------------------------
| 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('file-upload', [FileUploadController::class, 'fileUpload'])->name('file.upload');
Route::post('file-upload', [FileUploadController::class, 'fileUploadPost'])->name('file.upload.post');
Create FileUploadController
app/Http/Controllers/FileUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUpload()
{
return view('fileUpload');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUploadPost(Request $request)
{
$request->validate([
'file' => 'required|mimes:pdf,xlx,csv|max:2048',
]);
$fileName = time().'.'.$request->file->extension();
$request->file->move(public_path('uploads'), $fileName);
return back()
->with('success','You have successfully upload file.')
->with('file',$fileName);
}
}
Create Blade File
resources/views/fileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>laravel 8 file upload example - ItSolutionStuff.com.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>laravel 8 file upload example - ItSolutionStuff.com.com</h2></div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('file.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="file" class="form-control">
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>

Laravel Backpack is for admin CRUD functionalities. All you need to do in the admin controller is to define the field type as "Browse" for file upload. Example, below is to upload and file. It will upload single file in your laravel default filesystem and save the path in photo_path field of database.
$this->crud->addField([ // Photo
'name' => 'photo_path',
'label' => "Photo",
'type' => 'browse'], 'both');
This is for the admin only, if you want upload feature for frontend, Backpack API's are not for that. In that case, check in Laravel docs.

Related

How to upload image to Laravel storage?

I'm trying to implement this guide on how to upload an image to the laravel storage but when I submit, it shows that the page is expired. There is not error report in the log which makes it difficult to debug.
web.php:
Route::get('/upload-image', [StorageController::class, 'index']);
Route::post('/save', [StorageController::class, 'save']);
StorageController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
use App\Models\Photo;
class StorageController extends Controller
{
public function index()
{
return view('image');
}
public function save(Request $request)
{
$validatedData = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
$name = $request->file('image')->getClientOriginalName();
$path = $request->file('image')->store('public');
$save = new Photo;
$save->name = $name;
$save->path = $path;
$save->save();
return redirect('upload-image')->with('status', 'Image Has been uploaded');
}
}
Model Photo.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
use HasFactory;
}
Laravel view to upload the image image.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Uploading Image</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
#if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<div class="card">
<div class="card-header text-center font-weight-bold">
<h2>Laravel 8 Upload Image Tutorial</h2>
</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="file" name="image" placeholder="Choose image" id="image">
#error('image')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
So when I navigate to localhost/upload-image it shows the view and I can choose a file in the input form but as soon as I click on the submit button, the page navigates to /save and shows 419 | Page Expired with no log entry. The browser console shows:
POST http://127.0.0.1:8000/save 419 (unknown status)
You are not passing #csrf token in form request:
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
#csrf
Please pass as per above code example then it will be work.
You should include #csrf in your form tags.
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
#csrf
</form>

Laravel 5.8 image upload

After creating a Laravel site with user login, I wanted to add file upload ability. I followed a simple tutorial but when it came to do php artisan migrate it didn’t work because Base table or view already exists so I created an images table manually in MySQL.
Finally, I navigated to my websites image upload page http://localhost/sites/mywebsite/public/image and attached an image. The error I got was The POST method is not supported for this route. Supported methods: GET, HEAD.
This is the line in my image.blade.php file:
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
Note; When I created an images table manually in MySQL I only added 'id' and 'image' columns and I wasn't 100% sure how to format them.
Any help very much appreciated.
Here's my ImageController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator, Redirect, Response, File;
use App\Image;
class ImageController extends Controller
{
public function index()
{
return view('image');
}
public function save(Request $request)
{
request()->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($image = $request->file('image')) {
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert[]['image'] = "$profileImage";
}
}
$check = Image::insert($insert);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
}
Image.blade.php
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.container {
padding: 10%;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2 style="margin-left: -48px;">Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Opps!</strong> There were something went wrong with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br>
#endif
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
#csrf
<div class="avatar-upload col-6">
<div class=" form-group avatar-edit">
<input type='file' id="image" name="image[]" accept=".png, .jpg, .jpeg" />
<label for="imageUpload"></label>
</div>
</div>
<div class="form-group col-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>
Migration table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->increments('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Follow Any Method :
<form action="{{ url('save') }}" method="get" accept-charset="utf-8" enctype="multipart/form-data">
And Change Migartion $table->text('image');
OR
Route::post('save', 'ImageController#save');
And Change Migartion $table->text('image');
You need to create a POST method route in routes/web.php.
A get route does not support posting form data
Route::post('save', 'ImageController#save');
Also, the image column in your database should be a string, an integer can't hold a path to a file
$table->string('image');
But you can't insert an array to a string column anyway so you should move the Model create method inside the foreach loop
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
Image::insert($profileImage);
}

Laravel page not found at create function

Recently I started programming using Laravel as a framework. Everything goes fine, but I tried to write a create script with the following message at runtime:
Sorry, the page you are looking for could not be found.
That's after posting Accept in the Create form, I already have created Index, Show, Update and delete functions successfully. So the route to my controller is correct, the file exist ... I'm totally stuck and can not see what incorrect.
Please help.
I didn't redirect the public folder so I'm still using the full path with no problem at the other modules (/gymmgr/public/lockers).
I send you the code:
index.blade.php
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Lockers</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/lockers/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Clave del locker</th>
<th>Ubicación</th>
</tr>
</thead>
<tbody>
#foreach($lockers as $locker)
<tr>
<td> {{ $locker->strClaveLocker }} ></td>
<td>{{ $locker->strUbicacion }}</td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
LockersController.php
<?php
namespace App\Http\Controllers;
use App\Locker;
use Illuminate\Http\Request;
class LockersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$lockers = Locker::all();
return view('lockers.index', ['lockers'=>$lockers]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('lockers.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
/*
if (Auth::check())
{*/
$locker = Locker::create(
['strClaveLocker'=>$request->input('strClaveLocker'),
'strUbicacion'=>$request->input('strUbicacion')
]
);
if($locker)
{
return redirect()->route('lockers.index')->with('success','Locker creado con éxito');
}
// }*/
}
/**
* Display the specified resource.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function show(Locker $locker)
{
//
$locker = Locker::find($locker->idLocker);
//$locker = Locker::where('idLocker', $locker->idLocker)->first();
//echo e($locker->idLocker);
return view('lockers.show', ['locker'=>$locker]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function edit(Locker $locker)
{
//
$locker = Locker::find($locker->idLocker);
if ($locker)
{
return view('lockers.edit', ['locker'=>$locker])->with('success', 'Locker encontrado');
};
return view('lockers.edit', ['locker'=>$locker]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Locker $locker)
{
//
$lockerUpdate = Locker::where('idLocker', $locker->idLocker)->update([
'strClaveLocker'=>$request->input('strClaveLocker'),
'strUbicacion'=>$request->input('strUbicacion')]);
if ($lockerUpdate)
{
return redirect()->route('lockers.show',['lockers'=>$locker->idLocker])
->with('success', 'Locker actualizado correctamente');
}
return back()->withInput();
}
/**
* Remove the specified resource from storage.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function destroy(Locker $locker)
{
//
$findLocker = Locker::find($locker->idLocker);
if($findLocker->delete())
{
return redirect()->route('lockers.index')
->with('success','Locker borrado exitosamente');
}
return back()->withInput()->with('error','El locker no pudo borrarse');
}
}
create.blade.php
#extends('layouts.app')
#section('content')
#guest
#else
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Locker') }}</div>
<div class="card-body">
</form>
<form method="post" action="{{ route('lockers.create') }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="put">
<div class="form-group">
<label for="locker-clave">Clave del locker<span class="required">*</span></label>
<input placeholder="Clave del locker"
id="locker-clave"
required
name="strClaveLocker"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="locker-ubicacion">Ubicación del locker</label>
<input placeholder="Ubicación del locker"
id="locker-ubicacion"
required
name="strUbicacion"
class="form-control"
/>
</div>
<div class="form-group">
<input type="submit"
class="btn btn-primary"
value="Aceptar"
/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endguest
#endsection
The route
web.php
/*
|--------------------------------------------------------------------------
| 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('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('lockers','LockersController');
Your create form has:
<form method="post" action="{{ route('lockers.create') }}">
...
<input type="hidden" name="_method" value="put">
So you are sending a PUT request to your create route. As the docs describe, the .create route the resource declaration sets up is expecting a GET (check the table of actions it sets up). So that request will fail with a 404 as there is no matching route set up.
Also, though confusingly named, the create route is for displaying the create form, not saving data you've entered into that form. So you should not be submitting data to your create route.
You need to:
Change your form action to point to your store route: ... action="{{ route('lockers.store') }}
Remove the form method spoofing, store expects POST which is what you'll get by default without any spoofing.

Error while submitting form Laravel 5.6

I have code in router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code in UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
return view('admin.add-user')->withInput();
}
}
Code in AddUserRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'required|same:pass1',
];
}
}
Code view errors:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
When running the path: http://localhost/LBlog/public/admin/manage-user/add and submit (Do not enter form information), the screen returns error: The page has expired due to inactivity. Please refresh and try again.
I hope someone can help me with this issue
That error appears due to CSRF token.
Add csrf token in your form.
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
#csrf
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>

Laravel localization

I'm going crazy with Laravel's localization system, but I don't know what's wrong with my code.
I just wrote a language-chooser, in the Head of the document you'll see a function to get the Browser-default language, which shall get the default language.
The Language-Templates are saved as default in an array in the /resources/lang/*language*/messages.php-files.
I really need your help, because I can't see any errors.
<html>
<head>
<?php
//get Browser default language
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
App::setlocale($lang);
?>
</head>
<body>
<div class="container">
#yield('content')
<div class="well text-center">
<h1><?php echo trans('Welcome') ?></h1>
</div>
#section('content.welcome')
<div class="row text-center">
Deutsch
<label> | </label>
English
<label> | </label>
Italiano
<label> | </label>
Español
<label> | </label>
Français
<label> | </label>
日本人
<label> | </label>
Pусский
</div>
#show
</div>
#section('footer')
<nav>
© <?php echo date("Y"); ?>
<ul >
<li >
<?php echo trans('Contact') ?>
</li>
</ul>
</nav>
#show
</body>
As per my understand, you need to modify your current approach. So, here is the example you can utilize for project.
.Env
APP_LOCALE=en
config/app.php
'locale' => env('APP_LOCALE', 'en'),
HTML
<ul class="dropdown-menu" role="menu">
<li>{!! link_to('lang/en', trans('menus.language-picker.langs.en')) !!}</li>
<li>{!! link_to('lang/es', trans('menus.language-picker.langs.es')) !!}</li>
<li>{!! link_to('lang/fr-FR', trans('menus.language-picker.langs.fr-FR')) !!}</li>
<li>{!! link_to('lang/it', trans('menus.language-picker.langs.it')) !!}</li>
<li>{!! link_to('lang/pt-BR', trans('menus.language-picker.langs.pt-BR')) !!}</li>
<li>{!! link_to('lang/ru', trans('menus.language-picker.langs.ru')) !!}</li>
<li>{!! link_to('lang/sv', trans('menus.language-picker.langs.sv')) !!}</li>
</ul>
Route
get('lang/{lang}', 'LanguageController#languageRoute');
LanguageController
namespace App\Http\Controllers;
class LanguageController extends Controller
{
function languageRoute($lang)
{
session()->put('locale', $lang);
return redirect()->back();
}
}
LocaleMiddleware
namespace App\Http\Middleware;
use Closure;
class LocaleMiddleware
{
protected $languages = ['en', 'es', 'fr-FR', 'it', 'pt-BR', 'ru', 'sv'];
public function handle($request, Closure $next)
{
if(session()->has('locale') && in_array(session()->get('locale'), $this->languages))
{
app()->setLocale(session()->get('locale'));
}
return $next($request);
}
}
add middleware to kernel.php
And Finally , my lang folder looks like
en
es
fr-FR
it
pt-BR
ru
sv
and each folder contains:
alerts.php
auth.php
crud.php
labels.php
menus.php
navs.php
pagination.php
passwords.php
roles.php
strings.php
validation.php
Hope, this example help you much, but however it's just a example still you can update as per your requirement. If still something confused please let me know, I will try to update question in further detail.

Resources