Laravel - dont update photo if $request->file('photo') is null - php

Here I have Laravel update function,so with this function I update fields and here is imporant input PHOTO
My code is:
public function update($id, Requests\ArticleRequest $request)
{
$this->validate($request, [
'photo' => 'image|max:10000',
// validate also other fields here
]);
// checking file is valid.
if (!$request->file('photo')->isValid()) return redirect()->back()->withErrors(["photo" => "File is corrupt"]);
// file is valid
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$filename = str_random(5).'.'.$extension; // give a name to the image
$request->file('photo')->move($destinationPath, $filename); // uploading file to given path
// sending back with message
$article = Auth::user()->articles()->findOrFail($id); //if article id is unique just write Article::findOrFail($id)
$article_fields = $request->except('photo');
$article_fields['photo'] = $filename;
$article->update($article_fields);
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
so when I choose some image to update photo everything is fine,but when I want to update other fileds and photo to stay the same at database... I get error:
Call to a member function isValid() on a non-object
How I can skip photo if $request->file('photo') is blank, so no new image choosen...

public function update($id, Requests\ArticleRequest $request){
**//check if file provided**
if ($request->hasFile('photo')) {
$this->validate($request, [
'photo' => 'image|max:10000',
// validate also other fields here
]);
// checking file is valid.
if (!$request->file('photo')->isValid()) return redirect()->back()->withErrors(["photo" => "File is corrupt"]);
// file is valid
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$filename = str_random(5).'.'.$extension; // give a name to the image
$request->file('photo')->move($destinationPath, $filename); // uploading file to given path
// sending back with message
$article = Auth::user()->articles()->findOrFail($id); //if article id is unique just write Article::findOrFail($id)
$article_fields = $request->except('photo');
$article_fields['photo'] = $filename;
$article->update($article_fields);
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
Alert::message('Nothing to update', 'So sad!');
return redirect('auctions');
}

Related

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);
}

How to upload Image in Database in Laravel 5.7?

I'm making an app in Laravel 5.7 . I want to upload image in database through it and I want to show it from database.
I have tried different methods around the Internet as I was getting issues in
Intervention\Image\Facades\Image
I followed many advices from Internet make changes in config.app
made changes in Composer
At the end used
use Intervention\Image\Facades\Image as Image;
So I get resolved from issue "Undefined class Image"
but now I' m getting issues as "Undefined class File",
Method getClientOriginalExtension not found.
Method Upsize, make not found.
My code is
<?php
namespace App\Http\Controllers;
use File;
use Intervention\Image\Facades\Image as Image;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
//
protected $user;
/**
* [__construct description]
* #param Photo $photo [description]
*/
public function __construct(
User $user )
{
$this->user = $user;
}
/**
* Display photo input and recent images
* #return view [description]
*/
public function index()
{
$users = User::all();
return view('profile', compact('users'));
}
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
//setting flag for condition
$org_img = $thm_img = true;
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/originals/')) {
$org_img = File::makeDirectory('images/originals/', 0777, true);
}
if ( ! File::exists('images/thumbnails/')) {
$thm_img = File::makeDirectory('images/thumbnails', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->user;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/originals/' . $filename;
$thm_path = 'images/thumbnails/' . $filename;
$newPhoto->image = 'images/originals/'.$filename;
$newPhoto->thumbnail = 'images/thumbnails/'.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if (($org_img && $thm_img) == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
Image::make($image)->fit(270, 160, function ($constraint) {
$constraint->upsize();
})->save($thm_path);
}
}
}
return redirect()->action('UserController#index');
}
}
Please suggest me any Image Upload code without updating repositories or suggest me how can I remove issues from this code.
The beginning of time read below link because laravel handled create directory and hash image and put directory
laravel file system
then read file name when stored on directory and holds name on table field when need image retrieve name field and call physical address on server
$upload_id = $request->file('FILENAME');
$file_name = time().$upload_id->getClientOriginalName();
$destination =
$_SERVER["DOCUMENT_ROOT"].'/adminbusinessplus/storage/uploads';
$request->file('FILENAME')->move($destination, $file_name);
$string="123456stringsawexs";
$extension = pathinfo($upload_id, PATHINFO_EXTENSION);
$path = $destination.'/'.$file_name;
$public =1;
$user_id = $request->logedin_user_id;
$hash = str_shuffle($string);
$request->user_id = $request->logedin_user_id;
$request->name = $file_name;
$request->extension = $extension;
$request->path = $path;
$request->public = $public;
$request->hash = $hash;
//$request INSERT INTO MODEL uploads
$file_id = Module::insert("uploads", $request);

How to validate image store in Controller in Laravel 5.6

in My laravel 5.6 app I have image store function in my Controller like this,
public function store(Request $request)
{
$image = new Category();
if ($request->hasFile('image')) {
$dir = 'images/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
}
$image->save();
}
now I need validate before save image if saving without image (empty) and if not file format is equel to (png,jpeg,png). how can I do this?
In the first line of your function
$validatedData = $request->validate([
'image' => 'required|file|mimes:jpeg,png'
]);
//image is valid
Take a look at this: docs
You can do this:
//first you should use the Request class at the top of your file
use Illuminate\Http\Request;
public function store(Request $request)
{
$validator = $request->validate([
'image' => 'required|image'
]);
if ($validator->fails()) {
// write what you want here
}
// the rest of your code
}
The file under validation must be an image (jpeg, png, bmp, gif, or svg).

The image path in the database is not saved

I want to upload a photo along with a text
But the photo path is not saved inside the table, but the photo is uploaded to the directory
Controller code
namespace App\Http\Controllers;
use App\Http\Requests\singlereq;
use App\infouser;
class singleupload extends Controller
{
public function uploadform()
{
return view('singleupload.upload_form');
}
public function uploadSubmit(singlereq $request)
{
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$product = infouser::create($request->all());
return 'OK Upload successful!';
}
}
Used below code. to get the image name and set the table column (your_file) your is column name in your table.
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$input = $request->all();
$name = $file->getClientOriginalName();
$input['your_file'] = $name;
$product = infouser::create($input);
return 'OK Upload successful!';

Getting files uploaded correctly using Laravel

I am having some trouble with a photo upload system I'm working on in Laravel. So far, I have the file coming in and saving in public/images/profiles just fine, but I can't figure out how to insert it into the db with the right information. Currently I'm getting a "Call to undefined method Illuminate\Database\Eloquent\Collection::save() " error.
In my controller, I am currently trying to insert it by doing this:
public function updatePhotos($id)
{
if(Input::hasFile('image'))
//If file is being added
{
$extension = Input::file('image')->getClientOriginalExtension();
$fileName = str_random(9).'.'.$extension;
$user = User::find($id);
$user->profile->photo->type = 1;
$user->profile->photo->filename = $fileName;
$user->profile->photo->save();
Input::file('image')->move('public/images/profiles/',$fileName);
}
}
In the Photo model:
public function profile()
{
return $this->hasOne('Profile');
}
In the profile model, I have:
public function photo()
{
return $this->hasMany('Photo','user_id','user_id');
}
Could anybody send me on the right course for this?
Thanks
You are trying to save the user model, you have to create a new photo model, fill it with data and save it.
public function updatePhotos($id)
{
$image = new Image();
$image->user_id = Auth::id();
$image->fill(Input::all());
if (Input::hasFile('file')) {
$file = Input::file('file');
$image->extension = $file->guessClientExtension();
$image->size = $file->getClientSize();
$image->filename = str_random(9) . '.' . $image->extension;
$uploadSuccess = $file->move('public/images/profiles/', $image->filename);
$image->save();
$user = User::find($id);
$user->image = $image->id;
$user-save();
}
}
}
New image object created.
Field user_id on image object is set to the current users ID.
All fillable fields are filled with data from the form.
If input has file, file is set to $image->user_id = Auth::id();
Image extension, size and filename is set on image object.
Image is moved (placed) in public/images/profiles/ folder.
Image object is saved.
Get user object, assign image field with image ID and save user object.

Categories