I have no idea what this is doing:
$projects = Project::all();
$images = Image::all();
You want to select all from table prior to storing a new record?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello all I made a CRUD for my Image model to be able to upload image using a form and register the data of those images (name, path,etc..) in the following table in my MySql database:
CREATE TABLE IF NOT EXISTS `images` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`path` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`project_id` bigint(20) UNSIGNED DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `images_project_id_foreign` (`project_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
The problem is than when I upload a image the name and the path have NULL value and I dont understand why because I checked and the $imageName and $pathImg in the controler seems to have the correct values.
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name', 'path','project_id'
];
}
Controler:
public function store(Request $request)
{
$projects = Project::all();
$images = Image::all();
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('image'), $imageName);
$pathImg="/image/$imageName/";
$request->validate([
'name' => $imageName,
'path' => $pathImg,
]);
Image::create($request->all());
return view('gallery')
->with('success','You have successfully upload image.')
->with('image',$pathImg)
->with('images',$images)
->with('projects',$projects);
}
my form:
<form method="POST" action="{{ route('image.store') }}" enctype="multipart/form-data">
@csrf
<input type="file" class="form-control" name="image" />
<input type="hidden" id="version" name="project_id" value="{{ $project->id }}" />
<button type="submit" class="btn btn-sm">Upload</button>
</form>
``
rearrange your file, you have multiple things confused;
public function store(Request $request)
{
if($request->hasFile('image') {
$request->validate([
'image' => 'image',
]);
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('img'), $imageName);
$pathImg="/img/$imageName/";
Image::create([
'name' => $imageName,
'path' =< $pathImg
]);
}
return redirect()->route('projects.index');
}
Please or to participate in this conversation.