I want to update user image but it's not getting updated. I have used following controller for updating the image.. Can you suggest what's the mistake in controller function?
View part :
<div class="form-group">
<label>Image Upload</label>
<input type="file" name="image" id="image"><img src="{{ asset('public/images/' . $course->image) }}" width="200px"/></br>
</div>
Controller function :
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
}
$data->course_code = $request['course_code'];
$data->course_title = $request['course_title'];
$data->course_credit = $request['course_credit'];
$data->save();
return redirect('course');
}
Did you checked file permission on 'images' directory? It needs to have write permission for uploading files.
The problem is this,
$data->image = $name;
You set the value but you don't save it anywhere. You must add a saving line.
$data->save();
Note that, calling update() only saves what you pass in as parameters, doesn't save what you set through the mutators.
See The mistake/ solution of the problem is first i need to store the update value and then save the new image. So I made some changes in controller and solved it..
Here is controller code:
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
$data->update($request->all());
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
$data->save();
}
return redirect('course');
}
Related
I am trying to update an image and other data in a database, but when I update only text data, the image value becomes null or empty.
<form action="/admin/settings/why-us/update/{{$data->id}}" enctype="multipart/form-data" method="POST">
#csrf
<input type="text" class="form-control" name="title" value="{{$data->title}}">
<input type="file" class="form-control" value="{{$data->image}}" name="image">
<button type="submit" class="btn btn-success py-2 px-4 text-white">Update changes</button>
</form>
This a controller
public function updateWhyusPageSetting(Request $request,$id)
{
$title = $request->input('title');
$image = $image = $request->file('image');
dd($image);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('/frontend/images/'), $filename);
$image_upload = $request->file('image')->getClientOriginalName();
}
DB::table('features')
->where('id', $id)
->update([
'title' => $title,
'image' => $image_upload
]);
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
When I input only the title, left out the image, and tried to dump using dd($image);, I got a null value.
When updating the image, it's getting updated very well database.
Now, my question is, how do I make sure the value is captured in the input file <input type="file" class="form-control" value="{{$data->image}}" name="image"> so that when I update other data, it also sends the image value. NB: value="{{$data->image}}" IS NOT capturing the data from database
Try this code
public function updateWhyusPageSetting(Request $request,$id){
$data = [];
$data['title'] = $request->input('title');
if($request->hasFile('image')) {
$image = $request->file('image');
$image->move(public_path('/frontend/images/'),$imageName = $image->hashName()); //hashName() will generate image name with extension
$data['image'] = $imageName; // here if user uploads an image, it will add to data array then add to DB.
}
DB::table('features')
->where('id', $id)
->update($data); // if a user uploaded an image will add. if not, a previous image will not change
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
Please note you should delete the old images if you don't need anymore
you can use this to delete an old image if you want
(new Filesystem())->delete("full/path/with/image/name.jpg");
I'm trying to upload image-file from frontend in OctoberCMS
I have a model Person and relation:
public $attachOne = [
'photo' => 'System\Models\File'
];
In php-block with upload form:
public function onUploadImage() {
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = \Input::file('avatar');
$person->save();
}
And my template:
<form method="POST" action="/persons/person/{{person.id}}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_handler" value="onUploadImage">
<input type="file" name="avatar" id="avatar" />
{{ form_token() }}
{{ form_sessionKey() }}
<button type="submit" data-attach-loading>Upload</button>
After submit it saves to DB only path 'http://my-site/storage/app/uploads/public/' and does not upload any files to filesystem. It seems like there are no some permissions, but I can easily upload images from backend.
Where is my error?
You must get the UploadedFile from the request and store it to one of the configured disks. And store the path to the image in the database.
Assume storage/app/public/images is the directory where the uploaded images should be stored.
public function onUploadImage() {
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = request()->file('avatar');
$filename = $file->getClientOriginalName();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = $file->storeAs('images', $filename)
$person->save();
}
}
Here is the solution.
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = new System\Models\File;
$file->data = Input::file('avatar');
$file->is_public = true;
$file->save();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo()->add($file);
$person->save();
}
I made an update form wherein in i can edit and update current uploads in my renting shop project.
but i've been having this problem wherein the image isn't changing both in the page and database, but when i checked the storage/public/images it stores the same current image whenever i try to try again.
but the rest in my form is working fine and already changeable except the image.
Here is in my CarsController.php
public function update(Request $request, $id)
{
$car = Car::find($id);
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
if ($request->hasFile('image_location')) {
Storage::disk('public')->delete($car->image_location); // remove the old file.
$path = $request->image_location->store('images', 'public'); // save the new image.
$car->image_location = $path;
}
$car->save();
$request->session()->flash('message', 'The item has been updated.');
return redirect('/selections');
}
Here's the form
<div class="form-group">
<label>Image</label>
<input type="file" class="form-control" name="image_location" required>
</div>
i don't know what could possibly wrong. anyone please enlighten me. Thanks in advance. Anyway the migrated column name is image_location
also here's in my store()
public function store(Request $request)
{
$car = new car;
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
$path = $request->image_location->store('images', 'public');
$car->image_location = $path;
$car->availability = $request->availability;
$car->save();
$request->session()->flash('message', 'The item has been added.');
return redirect('/selections');
}
I'm afraid your code works perfectly for me.
You could try adding some log lines and see where the problem lies:
use Illuminate\Support\Facades\Log;
if ($request->hasFile('image_location')) {
Log::debug('File has been found in request.');
// Check if the old car image exists.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': ' does not exist'));
Storage::disk('public')->delete($car->image_location); // Remove the old file.
// Check if the old car image (if it existed) has been deleted.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': 'does not exist'));
$path = $request->image_location->store('images', 'public'); // save the new image.
// Check if the new file has been saved correctly.
Log::debug($path . (Storage::disk('public')
->exists($path)? ' exists': 'does not exist'));
$car->image_location = $path;
}
After uploading a new image, my storage/logs/laravel.log shows:
[2019-12-28 10:18:03] local.DEBUG: File has been found in request.
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif exists
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif does not exist
[2019-12-28 10:18:03] local.DEBUG: images/s9RtTdFSv0Is8AgxDWX5c09zG8SyU987RVeC0di5.gif exists
ERORR Undefined variable: listings
Users create a for sale advertising listing:
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
return view('user.dashboard');
After they get transferred to a dashboard page
#if($listings->isEmpty())
<div class="padding-top">
<h1 class="centre">None</h1>
</div>
#else
#endif
#foreach ($listings as $listing)
<div class="row">
<div class="container">
<div class="card">
<div class="card-body row">
<h5 class="card-title cardtitle col-lg-12 centre">{{$listing->address}}</h5>
incomplete html but just is an extract
EDIT ADDED FULL CONTROLLER Using return view('user.dashboard', ['listings' => $listing]); still throws an error
public function store(Request $request)
{
$this->validate($request, [
'image1' => 'image|nullable|max:1999',
'image2' => 'image|nullable|max:1999'
]);
// Handle File Upload
if($request->hasFile('image1')){
// Get filename with the extension
$filenameWithExt = $request->file('image1')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('image1')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('image1')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$listing = new Listings;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
$listing->image1 = $fileNameToStore;
return view('user.dashboard', ['listings' => $listing]);
}
Change
return view('user.dashboard');
into
return view('user.dashboard', compact('listing'));
I think the reason is pretty clear.
You need to pass $listing to your view like this:
return view('user.dashboard', compact('listing');
Edit:
Of course your variables must be named the same in your controller and view. You now have a mismatch as you name your variable $listing in your controller but call it as $listings in your view. Your code should be like this:
$listings->user_id = auth()->user()->id;
$listings->email= auth()->user()->email;
$listings->phone_number= auth()->user()->phone_number;
$listings->package = $request->session()->get('package');
$listings->save();
return view('user.dashboard', compact('listings');
Then you can call the variable as $listings in your view, so your view code doess not have to change.
EDIT 2:
$listing is ONE instance of the Listings model. So, you cannot call the empty() method on the object. I think you want to do something like this:
$listing = new Listings;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
$listing->image1 = $fileNameToStore;
$listings = Listings::all();
return view('user.dashboard', compact('listings'));
Does this work out for you?
Ps. Do you want to set the image1 attribute AFTER you save it? This will get lost.
I think you are not importing model in the controller using namespace.
try to check using "Use auth" namespace
use App\Listing_Model;
use auth;
class DashboardController extends Controller {
public function index() {
$listing = new Listing_Model;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
return view('user.dashboard');
}
}
I have a controller
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return redirect('settings/photos');
How can i redirect with the $image_ variable and display it in my view file
#foreach ($image_ as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</div>
#endforeach
You can use the compact function to pass it to your view and reference it by the name.
return redirect('folder.name', compact('variableName');
return redirect()->route('folder.name', [$image]);
You can also send variable using below syntax also
return view('viewfile')->with('card',$card)->with('another',$another);
You can send data using redirect method. Those data will store inside Session Class.
return redirect('url')->with('message',$message);
like below
Session::get('variableName');
Session::get('message');
You should try this:
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return view('yourfolder.yourviewfile',compact('image_'));
Updated Answer
use Redirect;
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
Redirect::to('settings/photos?image_='. $image_);
you can try with below code
return view('settings/photos')->with(['image' => $image_]);
Send an array of variables to your view:
return view('folder.viewfile', array(
'image_' => $image_,
'someother_variable' => $somevar,
));
Why you're using variable like this $image_ , you can use it simply like this $image or $whatEver
return view('folder.viewfile', compact('image'));
And now you can use this variable on view file as $image.
Do that in your controller function:
$request->session()->flash('order_id', $order_id);
And in view simply:
{{Session::get('order_id')}}
i just found myself in the same proble and solve with the help of you guys :)
on a complet example mi code ended like this:
mi FormCreate.php view recive an id from the previus page , so the url with out mask is "FormumariosCreate/16" in this example where the id is = 16 :
form:
<form method="post" action="{{ route('FormulariosStore2', $Formularios->idFormularios ) }}"> // is importan add the id on the rute
#csrf
<input type="text" name="textoPregunta" required="required" />
<button href="" class="btn btn-primary pull-right">Crear Nueva Pregunta</button>
</form>
rute in web.php:
Route::get('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
Route::post('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
and controler:
public function FormulariosStore2(Request $request,$id )
{
$validatedData = $request->validate([
'textoPregunta' => 'required|max:255',
]);
$ProyectoPreguntasF=ProyectoPreguntas::create($validatedData);
$Formularios = Formularios::findOrFail($id);
return redirect()->route('FormulariosCreate', $Formularios)->with('success','la operacion fue correcta.');
}
then it redirect to the rute "FormulariosCreate" with the id as a normal link with the id ,i hope it can add some content to the answer