I am facing this error while uploading an image with a title and description text to DB in PHP Laravel. I am using the same code for other webpage there it is working properly but the same code is not working here.
Below is a function code inside my controller, where I am passing tile, description, img and input names from a form.
public function submitFanfic(Request $request){
$user_id = session('userid');
$name = $_FILES['img']['name'];
$tem_name = $_FILES['img']['tmp_name'];
$dir = 'public/uploads/fanfic/';
$dir1 = $dir.$name;
move_uploaded_file($tem_name, $dir1);
$data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $name,
'user_id' => $user_id
);
DB::table('fanfic')->insert($data);
Session::flash('message', 'Fanfic Submitted Successfully');
return redirect('/author/write_fanfic');
}
I tried again and again and this code (specifically for image insertion into DB) worked!!
public function submitFanfic(Request $request){
$user_id = session('userid');
$imageName = $request->file('img');
if($imageName!==null){
// get the extension
$extension = $imageName->getClientOriginalExtension();
// create a new file name
$new_name = date( 'Y-m-d' ) . '-' . str_random( 10 ) . '.' . $extension;
// move file to public/images/new and use $new_name
$imageName->move( public_path('uploads/fanfic'), $new_name);
}
$fanfic_data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $new_name,
'user_id' => $user_id
);
DB::Table('fanfic')->insert($fanfic_data);
Session::flash('message', 'Fanfic Submitted Successfully');
Related
i want to update forums table that contains
fr_user_id
fr_author
fr_title
fr_body
fr_filename
code in my controller :
$request->validate([
'fr_user_id' => 'required',
'fr_author' => 'required',
'fr_title' => 'required',
'fr_body' => 'required'
]);
$input = $request->all();
if ($image = $request->file('fr_filename')){
$destinationPath = public_path('/images');
$imgName = time() . '.' . $image->getClientOriginalExtension();
$image->move($destinationPath, $imgName);
$input['fr_filename'] = "$imgName";
} else {
unset($input['fr_filename']);
}
$forum = Forum::find($id);
$forum->update($input);
return redirect('/user/myforum')->with('success','Update Successfull');
my Routes
Route::match(['put','patch'],'/forum/update/{id}',[ForumController::class,'update'])->name('forum/update');
this code is working but the 'fr_filename' data is become null in my db, what should i do?
Had you checked, file is coming in request?
I'm trying to upload files via API, in POSTMAN I can do it perfectly. However when doing in my application is not accepted.
Store in Controller:
public function store(Request $request)
{
$data = $request->validate([
'projeto_id' => 'required|integer',
'name' => 'required|string|max:255',
'logo' => 'nullable|image|mimes:jpeg,png,jpg|max:2000',
'telephone' => 'required|string|max:255',
'desc' => 'required|string',
'quantity' => 'required|integer|gt:0|lt:51',
'sequential' => 'required|integer|gt:0',
]);
$user = Auth::user()->id;
if($user != Auth::id()){
abort(403);
}
//UPLOAD IMAGEM DO GRUPO
$logo = $request['logo'];
// Check if a profile image has been uploaded
if ($request->has('logo')) {
// Get image file
$image = $request->file('logo');
// Make a image name based on user name and current timestamp
$name = Str::slug($user.'_'.time());
// Define folder path
$folder = '/uploads/images/'.$user.'/groupimg/logo/';
// Make a file path where image will be stored [ folder path + file name + file extension]
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
// Upload image
$this->uploadOne($image, $folder, 'public', $name);
// Set user profile image path in database to filePath
$logo = $filePath;
}
$gPrivado = '0';
if($request->has('private')){
$gPrivado = '1';
}
$i = 0;
$delayCounter = 0;
$sequential = $data['sequential'];
while ($i < (int)$data['quantity']) {
$delay = $delayCounter + rand(10, 15);
CreateGroups::dispatch($data['name'] . " {$sequential}", $logo , $data['desc'], $gPrivado, [$data['telephone']], $data['projeto_id'], auth()->user())
->delay(Carbon::now()
->addSeconds($delay));
$delayCounter = $delay;
$i++;
$sequential++;
}
return redirect()->back()->with('success', 'Grupos adicionados em fila de criação, aguarde alguns minutos .');
}
Use Job to proccess:
public function handle()
{
$user = $this->user;
if ($user->instance_connected) {
$ZApi = new ZApi($user->zapi_instance_id, $user->zapi_token);
$createdGroup = $ZApi
->createGroup($this->name, $this->phones);
sleep(3);
foreach($createdGroup->groupInfo as $informacoes){
$linkInvite = $ZApi->getGroupInvite($informacoes->id);
$idGroup = $informacoes->id;
}
//DESCRICAO DO GRUPO
$descricao = $this->desc;
$setDescricao = $ZApi->setGroupDescription($idGroup, $descricao);
//GRUPO PRIVADO
if ($this->private == '1'){
$grupoPrivado = $ZApi->setGroupMessages($idGroup, 'true');
$adminOnly = $ZApi->setGroupEdit($idGroup, 'true');
}
$setImg = $ZApi->groupImage($idGroup, $this->logo);
The last line send to API, I'm using Guzzle
And this is my API function
public function groupImage(string $groupId, string $value)
{
return $this->doRequest2('POST', "group-pic", [
'multipart' => [
[
'name' => 'phone',
'contents' => $groupId,
],
[
'Content-type' => 'multipart/form-data',
'name' => 'file',
'contents' => fopen('storage'.$value, 'r'),
]
]
]);
}
But get this error response
GuzzleHttp\Exception\ClientException Client error: POST http://localhost:8081/api/danilo/group-pic resulted in a 400 Bad Request response: {"status":"Error","message":"File parameter is
required!"}
Can someone help me?
I have a small app to sell online courses.
Everytime I reset my migrations by doing php artisan migrate:reset, I get this error if I try to update a field in my Ecourses edit blade file.
Here's my controller
public function update(Request $request, $id)
{
$slugify = new Slugify();
$this->validate($request, [
'name' => 'required',
'price' => 'nullable',
'category_id' => 'required',
'level_id' => 'required',
'subtitle' => 'required',
'description' => 'required',
'video_link' => 'required',
'document' => 'nullable|file',
'status' => 'required|integer'
]);
$ecourse = Ecourse::findOrFail($id);
$ecourse->name = $request->name;
$ecourse->slug = $slugify->slugify($request->name);
$ecourse->price = $request->price;
$ecourse->status = $request->status;
$ecourse->description = $request->description;
$ecourse->subtitle = $request->subtitle;
$ecourse->video_link = $request->video_link;
$ecourse->category_id = $request->category_id;
$ecourse->level_id = $request->level_id;
$document = $request->file('document');
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
$fileToDelete = 'public/ecourses-files'. '/' . $ecourse->document;
if (Storage::exists($fileToDelete)) {
Storage::delete($fileToDelete);
}
$ecourse->document = $file;
$ecourse->save();
return redirect()->route('admin.ecourses.index')->with('success','Formation mise à jour');
}
The error is due to this line $ecourse->document = $file; and to make it work I have to comment it, update my Ecourse blade and then uncomment it.
I really don't know what's happening here...
Any help or explanation would be appreciated.
Thanks and take care.
Well it looks like that $request->hasFile('document') return false in this case this block of code will never run
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
So there is no variable $file is defined, to solve this you can do
$file = null;
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
This will solve the problem but in case that column document cannot be null it will give you an error so you you will have to make it required in validation rules and check why $request->hasFile('document') returns false
Alternative solution, check $file with isset(), if not define then define it, as like :
if(!isset($file)){
$file = null;
}
$ecourse->document = $file;
There is an operator for this:
$course->document = $file ?? null;
I received help to solve how to delete files uploaded by using the Cakephp Upload package. However, there seems to be a problem with how I update the values of the photo and dir fields. By using unlink I was able to delete the files perfectly, but there seems to be a problem when I try to set the values to null. I made a function to test it out:
public function deletePhoto2($id)
{
// $this->request->allowMethod(['post']);
if ($this->request->is(['patch', 'post', 'put'])) {
$brigada = $this->Brigadas
->findById($id)
->firstOrFail();
$brigada->dir = null;
$brigada->photo = null;
if ($this->Brigadas->save($brigada)) {
$this->Flash->success(__('Your team data has been saved.'));
return $this->redirect(['action' => 'edit', $brigada->id]);
}
$this->set('brigada', $brigada);
}
}
Before saving I find that the value of $brigada->photo and $brigada->dir are null, but values don't save. I have several possibilities that want to explore but my knowledge of PHP is a hindrance:
I may be doing updates wrong. Link
I may need to use the deleteCallback which is documented here, but I don't know how to do it. I figured that it would be with $this->Brigadas->deleteCallback() or something similar, but I'd like to understand an example first, which is why I'm asking. I found no use of these callbacks in any example on the web, and the documentation on events is still a bit esoteric for me.
Here is how BrigadasTable.php is setup to upload files:
// http://josediazgonzalez.com/2015/12/05/uploading-files-and-images/
$this->addBehavior('Josegonzalez/Upload.Upload', [
'photo' => [
'fields' => [
'dir' => 'dir',
'size' => 'photo_size', // defaults to `size`
'type' => 'photo_type', // defaults to `type`
],
'nameCallback' => function ($table, $entity, $data, $field, $settings) {
if ($entity->gvCode){
$array = explode(".", $data['name']);
return strtolower($entity->gvCode) . '_' . date("Ymd-hisa") . '.jpg';
} else{
$array = explode(".", $data['name']);
$newArray = array_pop($array);
return strtolower(join('_', $array)) . '_' . date("Ymd-hisa") . '.jpg';
}
},
'transformer' => function ($table, $entity, $data, $field, $settings) {
$extension = pathinfo($data['name'], PATHINFO_EXTENSION);
// Store the thumbnail in a temporary file
$tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;
// Use the Imagine library to DO THE THING
$size = new \Imagine\Image\Box(640, 640);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine = new \Imagine\Gd\Imagine();
// Save that modified file to our temp file
$imagine->open($data['tmp_name'])
->thumbnail($size, $mode)
->save($tmp);
$filenameTmp = explode('.', $data['name']);
array_pop($filenameTmp);
$filenameTmp = join('_', $filenameTmp) . '.jpg';
// return debug($filenameTmp);
// Now return the original *and* the thumbnail
return [
$data['tmp_name'] => $filenameTmp,
$tmp => 'thumbnail-' . $filenameTmp,
];
},
'deleteCallback' => function ($path, $entity, $field, $settings) {
// When deleting the entity, both the original and the thumbnail will be removed
// when keepFilesOnDelete is set to false
$entity->{$field} = null;
return [
$path . $entity->{$field},
$path . 'thumbnail-' . $entity->{$field}
];
},
'keepFilesOnDelete' => false
]
]);
Thank you!
You can run an update query straight, instead of fetching the record, setting values and saving it.
$query = $this->Brigadas->query();
$query->update()
->set([
'dir' => null,
'photo' => null,
])
->where(<condition>)
->execute();
Incase any of your columns are json,
$query = $this->Brigadas->query();
$query->update()
->set([
'dir = null',
'photo' => null,
])
->where(<condition>)
->execute();
I am very new to PHP, I am using PHP Slim Framework. I have tried to research through Stack Overflow but didn't find an answer that answered my question.
I am trying add a car description on my school project, it captures all the fields well but the image is not being saved to the database and not being uploaded to the images folder, instead it saves the image in the database as a json as:
{
"car_images":
[
{
"file":"C:\\xampp\\tmp\\php8F2B.tmp"
}
]
}
instead of a91cffe8c9b5082f.jpg.
when I try to view the image in a browser on my localhost it goes to this path:
http://localhost/carbac/public/category_image/%7B%22car_images%22:[%7B%22file%22:%22C://xampp//tmp//php8F2B.tmp%22%7D]%7D
What could I be doing wrong?
Below is my function for capturing the details:
public function add(Request $request, Response $response, $args){
$car_category_id = $request->getParam('car_category_id');
$name = $request->getParam('name');
$description = $request->getParam('description');
$price = $request->getParam('price');
$mileage = $request->getParam('mileage');
$fuel_type = $request->getParam('fuel_type');
$transmission = $request->getParam('transmission');
$fuel_economy = $request->getParam('fuel_economy');
$air_condition = $request->getParam('air_condition');
$hourly_price = $request->getParam('hourly_price');
$daily_price = $request->getParam('daily_price');
$year = $request->getParam('year');
$directory = __DIR__ . '/../../../public/profile_image';
$uploadedFiles = $request->getUploadedFiles()['category_image'];
$avater = $request->getUploadedFiles();
foreach($uploadedFiles as $uploadedFile) {
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$avater[] = \App\Helpers\FileUpload::moveUploadedFile($directory, $uploadedFile, ['png', 'jpeg', 'gif', 'jpg']);
} else {
$Flash = new Flash();
$Flash->addMessage('message', "Sorry, something went wrong from our end, please notify site owner");
$Flash->addMessage('status', "callout-danger");
return $response->withRedirect($this->router->pathFor('car_description'));
}
}
if( ! $avater ) {
$Flash = new Flash();
$Flash->addMessage('message', "Sorry, Please make image you are uploading is either a 'png', 'jpeg' or 'gif'");
$Flash->addMessage('status', "callout-danger");
return $response->withRedirect($this->router->pathFor('car_description'));
}
$car_description = CarDescription::create([
'car_category_id' => $car_category_id,
'name' => $name,
'description' => $description,
'year' => $year,
'mileage' => $mileage,
'price' => $price,
'fuel_type' => $fuel_type,
'transmission' => $transmission,
'fuel_economy' => $fuel_economy,
'air_condition' => $air_condition,
'hourly_price' => $hourly_price,
'daily_price' => $daily_price,
'images' => json_encode($avater)
]);