Laravel problem store variables data in Database - php

In my database name files have columns id_message and file_path. File is stored in MyFiles/{id_message}.
Problem is how variables $idParameter and $pathFile save in database. No errors show.
function fileUpload(Request $request)
{
$request->validate([
'id_message' => 'required|min:6'
]);
$idParameter = $request->id_message=$request->id_message;
$result=$request->file('file_path')->store('MyFiles/'.$idParameter);
return ["result"=>$result];
$pathFile = getPathname('MyFiles/'.$idParameter);
$file = new File;
$file->id_message=$idParameter;
$file->file_path=$pathFile;
$file->save();
}

Remove return ["result"=>$result]; and add this into end.

Related

Laravel API store and retrieve base64 images in Storage

I am working with Angular and Laravel on a project where I have destinations table
And I need to store destinations, and for every destination there is multiple images I need to store
So there is destination_images table, I made one-to-many relationship between the tables
So I have two models: Destination - DestinationImage
The store Laravel function
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:100',
'description' => 'required'
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json($errors);
}
$destination = Destination::create([
'name' => $request->name,
'description' => $request->description
]);
foreach ($request->fileSource as $img_code) {
$ext = explode('/', mime_content_type($img_code))[1];
$img_name = uniqid() . ".$ext";
$decoded_img = base64_decode($img_code);
$path = Storage::put('uploads/destinations' . $img_name, $decoded_img);
DestinationImage::create([
'destination_id' => $destination->id,
'img' => $img_name
]);
}
return response()->json('Destination Added Successfully');
}
and it stores the file successfully but now I need to retrieve the images from Laravel storage and show it in Angular so I made this function
public function view($id) {
$destination = Destination::findOrFail($id);
$destination_images = $destination->destination_images;
foreach ($destination_images as $destination_image) {
$url = Storage::url($destination_image->img);
return response()->json($url);
}
}
but the response is not completed url it's just "/storage/62a7056a5d8c6.png"
Please anyone can help me how to maintain the view function to show the images in Angular?
You are using storage path mean while client can't access to it.
First you need to enable storage link php artisan storage:link and it should able to access http://yourdomain.com/storage/62a7056a5d8c6.png
$image = App\Models\DestinationImage::find(1);
echo url("/destination_images/{$image->id}");
use Illuminate\Support\Facades\Storage;
public function view($id) {
$destination = Destination::findOrFail($id);
$destination_images = $destination->destination_images;
$imageList = [];
foreach ($destination_images as $destination_image) {
$imageList[] = Storage::url($destination_image->img);
return response()->json($imageList);
}
}

Laravel uploading files and extension issue

I am trying to make store method where placing 2 different type of files - .pdf and .step.
First issue, that .pdf file is moved to wanted directory, but in database storing temporary location like C:\xampp\tmp\phpAA39.tmp etc...
At the start was same issue with .step files, but i tried to update my code and now it's not even storing path to database. Both files are placing to storage/models and storage/drawings how it should be, but .step files are saving as .txt by some reasons.
ProductController:
public function store(Order $order, Request $request){
$this->validate($request, [
'name'=>'required',
'drawing'=>'nullable|file',
'_3d_file'=>'nullable|file',
'quantity'=>'integer',
'unit_price'=>'required',
'discount'=>'nullable'
]);
if (request('drawing')) {
request('drawing')->store('drawings');
}
if (request('_3d_file')) {
request('_3d_file')->store('models');
}
// dd(request()->all());
$order->products()->create($request->all());
session()->flash('product-created', 'New product was added successfully');
return redirect()->route('order', $order);
}
Update:
Figured out, how to solve an extension and temp location stuff... but still don't understand why on my store method does not storing 3dfile path while with drawing is ok and code is exactly the same. Also on update method it stores path with no errors. Any thoughts?
public function store(Order $order){
$inputs = request()->validate([
'name'=>'required',
'drawing'=>'file',
'_3d_file'=>'file',
'quantity'=>'integer',
'unit_price'=>'required',
'discount'=>'nullable'
]);
if (request('drawing')) {
$filename = request('drawing')->getClientOriginalName();
$inputs['drawing'] = request('drawing')->storeAs('drawings', $filename);
}
if (request('_3d_file')) {
$filename = request('_3d_file')->getClientOriginalName();
$inputs['_3d_file'] = request('_3d_file')->storeAs('models', $filename);
}
//dd($inputs['_3d_file']);
$order->products()->create($inputs);
session()->flash('product-created', 'New product was added successfully');
return redirect()->route('order', $order);
}
update
public function update(Product $product){
$inputs = request()->validate([
'name'=>'required',
'drawing'=>'nullable|file',
'_3d_file'=>'nullable|file',
'quantity'=>'integer',
'unit_price'=>'required',
'discount'=>'nullable'
]);
if (request('drawing')) {
$filename = request('drawing')->getClientOriginalName();
$inputs['drawing'] = request('drawing')->storeAs('drawings', $filename);
$product->drawing = $inputs['drawing'];
}
if (request('_3d_file')) {
$filename = request('_3d_file')->getClientOriginalName();
$inputs['_3d_file'] = request('_3d_file')->storeAs('models', $filename);
$product->_3d_file = $inputs['_3d_file'];
}
$product->name = $inputs['name'];
$product->quantity = $inputs['quantity'];
$product->unit_price = $inputs['unit_price'];
$product->discount = $inputs['discount'];
$product->save();
session()->flash('product-updated', 'The product was updated successfully');
return redirect()->route('product', $product);
}

Validated and uploaded image incorrect name saved in MySQL in Laravel 6

Validation of text and photo takes place in StorePost FormRequest.
public function rules()
{
return [
'name' => 'required',
'exerpt => 'required',
'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
];
}
Then the controller part:
public function store( StorePost $request )
{
$imageName = time().'.'.$request->photo->extension();
$request->photo->move(public_path('post-images'), $imageName);
// may modify image name here but it's not elegant
//$data = $request->all();
//$data['photo'] = $imageName;
Post::create( $request->all() );
}
Image saves in MySQL as /private/var/folders/zr/y1drl_rs0sl75rxvgkx8ntzm0000gn/T/phpUJKeEG.
How can I set its name before the request gets to the controller?
I wouldn't like to do this such as here (commented lines).
You may use
$imageName = time().'_'.$request->photo->extension();
$request->photo->storeAs('public/post-images',$imageName);
$post = new Post;
//...
$post->photo = $imageName;
//...
$post->save();

Image update and remove old image on Laravel

Trying to implement update article in my update controller it seems works, but the problem is when I only want to update the post without uploading an image the old always getting remove which is it shouldn't.
here's my store function
public function store(Post $post)
{
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'New ariticle has been posted');
}
}
here's my validation
private function validateRequest()
{
return request()->validate([
'title'=> 'required',
'content' => 'required',
'image' => 'sometimes|image|max:5000',
]);
}
here's my update function
public function update(Post $post)
{
File::delete(public_path('storage/'.$post->image));
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'This post has
been Edited');
}
}
I've tried to add File::delete to my storeImage function and delete it from my update function, it fix the problem but the old image is not removed from directory
private function storeImage($post)
{
if (request()->has('image')){
File::delete(public_path('storage/'.$post->image))
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}
Ok since I use model binding in my controller I don't have to find the id right?
so I change my update function which is basically Akhtar munir suggested, and turn out to be something like this. The image update work, it also remove the old image when I update it. But I have found another issue, the problem is when I edit article and title it didn't change like when I update it, I hope you can take look at this is this correct?
public function update(Post $post){
$this->validateRequest();
if(request()->hasFile('image') && request('image') != ''){
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$post->update([
'title' => request()->title,
'content' => request()->content,
'image' => $image,
]);
}
}
This is what I have done in one of my method. It may help you.
public function update(Request $request, $id)
{
if (UserDocument::where('id',$id)->exists()) {
$this->validateUserDocument($request);
if ($request->hasFile('doc_file') && $request->doc_file != '') {
$doc = UserDocument::where('id',$id)->first();
// dd($doc);
$file_path = storage_path().'/app/'.$doc['doc_file'];
//You can also check existance of the file in storage.
if(Storage::exists($file_path)) {
unlink($file_path); //delete from storage
// Storage::delete($file_path); //Or you can do it as well
}
$file = $request->file('doc_file')->store('documents'); //new file path
$doc->update([
'title' => $request->title,
'doc_file' => $file //new file path updated
]);
session()->flash('success','Document updated successfully!');
return redirect()->route('userdocs');
}
session()->flash('error','Empty file can not be updated!');
return redirect()->back();
}
session()->flash('error','Record not found!');
return redirect()->back();
}
In this code, I just simply want to clearify to you that I have stored image path in database, first I have retrieved that path and with that path I have found image in my local storage, delete it first and then update it with the new one. But make sure to store image path in database in both cases ofcourse with insert and update.
So finally you can also optimize your code like this, it will do the same thing as you expect, whether image and all data or only title and content.
public function update(Post $post){
$this->validateRequest();
$data = [
'title' => request()->title,
'content' => request()->content
];
if (request()->hasFile('image') && request('image') != '') {
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$data['image'] = $image;
//$post->update($data);
}
$post->update($data);
}
Try this one
private function storeImage($post)
{
if (request()->hasFile('image')){
$image_path = "/storage/".'prev_img_name'; // prev image path
if(File::exists($image_path)) {
File::delete($image_path);
}
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}

How to make Laravel controller store file upload with a relationship

I am trying to store an uploaded file with a relationship to an Employee model. I am unable to retrieve the employee id after uploading the file to save it to the DB table as a foreign key.
Routes:
Route::resource('employees', 'EmployeesController');
Route::post('documents', 'DocumentsController#createdocument')
So I am on a URL that says http://localhost/public/employees/8 when I hit upload it redirects to http://localhost/public/documents and the file does upload but shows error when writing to DB.
Here is my code. How can I do it?
public function createdocument(Request $request, Employee $id)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
];
$this->validate($request, $rules);
$time = time(); // Generates a random string of 20 characters
$filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with
$destinationPath = config('app.fileDestinationPath').'/'.$filename;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded){
$employee = Employee::find($id);
$empdoc = new EmpDocuments();
$empdoc->name = $filename;
$empdoc->employee_id = $employee->id;
$empdoc->save();
}
return redirect('employees');
}
These are my models.
Employee.php
public function EmpDocuments()
{
return $this->hasMany('App\EmpDocuments');
}
public function createdocument(){
return $this->EmpDocuments()->create([
'name' => $filename,
'employee_id' => $id,
]);
}
EmpDocuments.php
public function Employee()
{
return $this->belongsTo('App\Employee');
}
With the above models and controller I am now getting error
General error: 1364 Field 'employee_id' doesn't have a default value (SQL: insert into empdocuments.
How do I capture the employee_id?
Managed to fix it, in case someone has similar problem. Ensure you pass the id with the route action for it to be capture in the next request.
Here is the final controller.
public function update(Request $request, $id)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
];
$this->validate($request, $rules);
$time = time(); // Generates a random string of 20 characters
$filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with
$destinationPath = config('app.fileDestinationPath').'/'.$filename;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded){
$employee = Employee::find($id);
$empdoc = new EmpDocuments();
$empdoc->name = $filename;
$employee->empdocuments()->save($empdoc);
return redirect('employees/' . $id . '#documents')->with('message','Document has been uploaded');
}
}
Do you have a relationship between Employee and EmpDocuments ??
If I am understanding well EmpDocuments belongsTO Employees right??
I'm trying to help but I need to understand, one employee can have many documents right?? but each document belongs to just one employee right??
If is like that you should make a relationship in your employee model,
` public function employeeDocuments(){
return $this->hasMany(EmpDocuments::class);
}`
Then in the same model
`public function createEmployeeDocuments(){
return $this->employeeDocuments()->create([
'your_db_fields' =>your file,
'your_db_fields' => your other some data,
]);
}`
The id will be inserted automatically
I hope I helped you!!
https://laravel.com/docs/5.3/eloquent-relationships
Are your fillable empty???
To use the Eloquent create method you need to set you fillable array to mass assignment. Try this, if is still not working tell me and I will try to do my best.
protected $fillable = [ 'employee_id', 'Your_db_field', 'Your_db_field', 'per_page', 'Your_db_field', 'Your_db_field' ];

Categories