Laravel image being posted to database as "/private/var/tmp/" - php

I'm trying to store an image in my Laravel project, but I'm having an issue. The image is sucessfuly being added to the /public/images folder as its filename, but when the request hits the database, its added as /private/var/tmp/XXXXX. I've tried to set $request->file as the name, but it still posts as the var/temp.
Controller
public function store(Request $request)
{
$rules = [
// 'address' => 'required',
// 'city' => 'required',
// 'postcode' => 'required',
// 'restDesc' => 'required',
// 'telNumb' => 'required',
// 'resWebsite' => 'required',
// 'restDesc' => 'required',
// 'business_id' => 'unique:busprofiles,business_id',
];
$customMessages = ["Message"];
if ($request->hasFile('file')) {
$request->file->store('public/uploads');
$filename = $request->file->getClientOriginalName();
$filesize = $request->file->getClientSize();
$request->file = $request->file->storeAs('public/uploads', $filename);
}
$this->validate($request, $rules, $customMessages);
Busprofile::create($request->all());
return redirect()->route('business.dashboard')
->with('success', 'Profile created successfully');
}
If it helps: return $request->file returns the correct URL.

The problem is in Busprofile::create($request->all());. You do indeed get the original filename with $filename = $request->file->getClientOriginalName(); but your request stays the same.
Create the array for the database entries manually, according to your database needs.
$data = ['filename' => $request->file->getClientOriginalName(),
...,
];
and
Busprofile::create($data);

Related

i have problem with laravel fileupload image

can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}

i am trying to save the image using the `Intervention \ Image library`. and I found an error Image source is not readable

public function store(Request $request)
{
$this->validate($request, [
'judul' => 'required',
'category_id' => 'required',
'konten' => 'required',
'gambar' => 'required',
]);
$gambar = $request->gambar;
$new_gambar = time().$gambar->getClientOriginalName();
$post = Posts::create([
'judul' => $request->judul,
'category_id' => $request->category_id,
'konten' => $request->konten,
'gambar' => 'public/uploads/posts/'.$new_gambar,
'slug' => Str::slug($request->judul),
'users_id' => Auth::id()
]);
$img = Image::make('public/uploads/',$gambar->getRealPath())->resize(300,
300)->save('public/uploads/', $gambar->getClientOriginalName());
$gambar->move('uploads', $new_gambar);
$post->tags()->attach($request->tags);
return redirect('post');
}
Add enctype in your html form
enctype="multipart/form-data"
And change for this in your controller:
$img = Image::make($request->file('gambar')->getRealPath());
Also check permissions of the directory in which you are uploading the file
make sure form has enctype:
<form class="form" ... enctype="multipart/form-data">
change controller
use Intervention\Image\ImageManagerStatic as Image;
public function store(Request $request)
{
$this->validate($request, [
// 'judul' => 'required',
//if judul column type is varchar need to set max varchar value or less
//varchar max 255, if higer than 255 strings, extra string will be truncated
'judul' => 'required|string|max:200',
// 'category_id' => 'required',
//category should exist
'category_id' => 'required|exists:categories,id',
'konten' => 'required',
// 'gambar' => 'required',
//validating image is successfully uploaded and is image format
'gambar' => 'required|file|image|mimes:jpg,jpeg,png',
//validation for tags, assuming 1 input <select name="tags[]" multiple="multiple"/>
'tags' => 'array',
'tags.*' => 'exists:tags,id'//each value of input select exists in tags table
]);
// $gambar = $request->gambar;
//get the file from <input type="file" name="gambar"/>
$gambar = $request->file('gambar');
$new_gambar = time().$gambar->getClientOriginalName();
//make path to save image: sample public path
$file_path = public_path("uploads/post/{$new_gambar}");
$img = Image::make($gambar)
->resize(300,300)
->save($file_path);
$post = Posts::create([
'judul' => $request->judul,
'category_id' => $request->category_id,
'konten' => $request->konten,
// 'gambar' => 'public/uploads/posts/'.$new_gambar,
//should maake the image first
'gambar' => $file_path,
'slug' => Str::slug($request->judul),
'users_id' => Auth::id() // <- if it is to get current logged in user, use Auth::user()->id
]);
// $gambar->move('uploads', $new_gambar); //let Intervention do this for you
// $post->tags()->attach($request->tags);
//if tags exists (get values frominput select)
$post->tags()->sync($request->input('tags', []));
//$request->input('tags', []) <- if input tags is not null get value, else use empty array
//if route have name e.g Route::get('post', 'PostController#post')->name('post');
//return redirect()->route('post');
return redirect('post');
}

Unable to obtain instance of HTTP request in Laravel 5.8

I am having trouble retrieving form values using the Illuminate\Http\Request class.
I have an endpoint that creates a product and another that updates it set up like this
Route::post('products', 'ProductController#store');
Route::put('products/{product}', 'ProductController#update');
The store and update methods in the ProductController are
public function store(Request $request)
{
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
public function update(Request $request, Product $product)
{
// dd($request);
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// update this product
if ($product) {
$product->update($request->all());
return new ProductResource($product);
} else {
return response()->json(["error" => "Not found"], 404);
}
}
Now when I test the endpoints in postman, I can successfully create a new product record. But if I try to update a product, I get a 401 unauthorized error even though all the required fields are filled. dd($request)returns null but dd($product) returns the product as expected.
Maybe I have been looking at it so hard so I have missed something. What am I doing wrong?
This is the reasons I think why the $request return null
The store and update request is same name. Two input name or select name or textarea name can't be the same name in the same web page. If its same it will always get the first one that is the reason why it is returning null because the first one is empty.
The name you're calling is incorrect
Hope it helps!

SQL default value error when uploading files using laravel

i'm trying to upload multiple images using laravel and so far i've succeded, but the problem is that when i try to save text AND the files i get an error.
So far i've received so many errors that i can't remember all of then, but the latest is:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts (image, updated_at, created_at) values (["italian.jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))
i've set the sql properly, and as i said, if i remove the image upload it works, and if i remove the text fields it also work, but if i try both i doesnt.
if i remember correctly when i remove the required fields it also works.
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'title' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if($request->hasfile('image')){
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
} else{
redirect('/posts')->with('Error', 'no image');
}
$post->image=json_encode($data);
$post = Post::create($validatedData);
return redirect('/posts')->with('success', 'yay');
}
i also tried this, but it returns
Creating default object from empty value
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|min:3|max:120',
'category' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post = new Post();
$post->image=json_encode($data);
$post->save();
return back()->with('success', 'Yay');
}
i figured it out, hehe. just had to remove these lines:
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
Thanks anyways.

Laravel File Upload Validation

I'm new to Laravel. I have a form with a File upload function on it. How can I validate their file? I will only allowed Microsoft Word files. Here's my validation code.
I just want check if they insert a ms word file and if not it will not be processed.
public function store()
{
// Validate
$rules = array(
'pda' => 'required|unique:forms',
'controlnum' => 'required|unique:forms',
'date' => 'required',
'churchname' => 'required',
'title' => 'required',
'pastorname' => 'required',
'contactnum' => 'required',
'address' => 'required',
'state' => 'required',
'region' => 'required',
'area' => 'required',
'city' => 'required',
'zipcode' => 'required|numeric|max:9999',
'tgjteachertraining' => 'required',
'localcontact' => 'required',
'tgjdatestart' => 'required',
'tgjdateend' => 'required',
'tgjcourse' => 'required|numeric',
'childrengraduated' => 'required|numeric|max:450',
'childrenacceptjesus' => 'required|numeric',
'howmanycomitted' => 'required|numeric',
'recievedbibles' => 'required|numeric',
'descgradevent' => 'required',
'whatwillyoudo' => 'required',
'pastortest' => 'required',
'teachertest' => 'required',
'childrentest' => 'required',
'file' => 'required|max:10000',
);
$validator = Validator::make(Input::all(), $rules);
// process the form
if ($validator->fails()) {
return Redirect::to('forms/create')->withErrors($validator);
} else {
// store
$forms = new Forms;
$forms->pda = Input::get('pda');
$forms->controlnum = Input::get('controlnum');
$forms->date = Input::get('date');
$forms->churchname = ucwords(Input::get('churchname'));
$forms->title = ucwords(Input::get('title'));
$forms->pastorname = ucwords(Input::get('pastorname'));
$forms->address = Input::get('address');
$forms->contactnum = Input::get('contactnum');
$forms->state = Input::get('state2');
$forms->region = Input::get('region2');
$forms->area = Input::get('area2');
$forms->citytown = Input::get('city2');
$forms->zipcode = Input::get('zipcode');
$forms->tgjteachertraining = Input::get('tgjteachertraining');
$forms->localcontact = ucwords(Input::get('localcontact'));
$forms->tgjdatestart = Input::get('tgjdatestart');
$forms->tgjdateend = Input::get('tgjdateend');
$forms->tgjcourse = Input::get('tgjcourse');
$forms->childrengraduated = Input::get('childrengraduated');
$forms->childrenacceptjesus = Input::get('childrenacceptjesus');
$forms->howmanycomitted = Input::get('howmanycomitted');
$forms->recievedbibles = Input::get('recievedbibles');
$forms->descgradevent = Input::get('descgradevent');
$forms->whatwillyoudo = Input::get('whatwillyoudo');
$forms->pastortest = Input::get('pastortest');
$forms->teachertest = Input::get('teachertest');
$forms->childrentest = Input::get('childrentest');
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$destinationPath = 'uploads/'.Input::get('pda');
$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
$forms->docurl = 'uploads/'.Input::get('pda').'/'.$filename;
if( $uploadSuccess ) {
$forms->save();
//Session::flash('message', 'Successfully submitted form!');
return Redirect::to('forms/create');
Session::flash('message', 'Successfully submitted form!');
}
else {
return Response::json('error', 400);
}
}
}
To validate mime type of a file input in Laravel you can use the mimes rule. Remember to match the mime type detected with the actual mime of file you provide. It may vary on different servers.
For example, you want to enable adding and word document in you form:
1) in config/mimes.php add the below mime types:
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
2) in your validation $rules add the following elements:
'file' => 'required|max:10000|mimes:doc,docx' //a required, max 10000kb, doc or docx file
Try this?
'file' => 'required|max:10000|mimes:application/vnd.openxmlformats-officedocument.wordprocessingml.document'
You may want to set some custom message for the response though :)
As of Laravel 9.22 you can write the validation rules a lot shorter and more readable like:
'file' => ['required', File::types(['doc', 'docx'])->smallerThan(10000)]
You can find the available methods in this pr: https://github.com/laravel/framework/pull/43271

Categories