Reputation: 1166
I'm trying to upload image for an icon image on my project. When POST this function i receive and error says
Laravel created by does not have a default value
when I already add the created_by field on my data list, below is my code :
public function postAddProject($dev_id)
{
$data = request()->validate([
'name' => 'required',
'address' => 'required|max:100',
'address2' => 'required_with:address3|max:100',
'address3' => 'nullable|max:100',
'zipcode' => 'required|numeric|digits:5',
'attachment' => 'mimes:jpeg,png'
]);
$data['developer_id'] = $dev_id;
$data['status'] = 'active';
$data['created_by'] = auth()->user()->id;
$project = Project::create($data);
if (!empty($data['attachment'])) {
$attachment_file = $data['attachment'];
$logo_file_contents = file_get_contents($attachment_file);
$imageData = [
'data' => $logo_file_contents,
'mime_type' => $attachment_file->getClientMimeType(),
'size' => mb_strlen($logo_file_contents),
'extension' => $attachment_file->getClientOriginalExtension()
];
// $imageData = self::optimizeImage($imageData);
$imageMedia = Media::create([
'category' => 'project-icon',
'mimetype' => $imageData['mime_type'],
'data' => $imageData['data'],
'size' => $imageData['size'],
'created_by' => auth()->user()->id,
'filename' => 'project_' . date('Y-m-d_H:i:s') . "." . $imageData['extension']
]);
$project->logo_media()->associate($imageMedia);
$project->save();
}
$dev_id = $project->developer_id;
return redirect()->route('admin.developers.projects.index', ['dev_id' => $dev_id])->withStatus(__('Admin successfully created.'));
}
Upvotes: 1
Views: 52
Reputation: 546
Try to add such code at the beginning of the script.
$user = auth()->user();
if(is_null($user)){
throw new \Exception('Error auth user');
}
$data['created_by'] = $user->id;
Upvotes: 1
Reputation: 1673
Created_by
is the table field which is used to mention the data created time . You should not overwrite it .
This field will be automatically filled by mysql
and laravel
.
You should add your user_id
in any other field like user_id
.
Just remove the following line .
$data['created_by'] = auth()->user()->id;
And create new field in table for user_id
and add auth()->user()->id
in that field .
Upvotes: 1