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 >
@if(session('status'))
<div >
{{ session('status') }}
</div>
@endif
<div >
<div >
<h2>Laravel 8 Upload Image Tutorial</h2>
</div>
<div >
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
<div >
<div >
<div >
<input type="file" name="image" placeholder="Choose image" id="image">
@error('image')
<div >{{ $message }}</div>
@enderror
</div>
</div>
<div >
<button type="submit" 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)
CodePudding user response:
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.