I receive all user activities for each image upload they make, but I also want to receive the image in this foreach along with the table.
In my database I have 5 columns within the users table, which are doc1 doc2 doc3 doc4 and doc5. As I receive the image made by them together with the correct description, without having to log in to each user account
in fact there are 5 controllers of these, please don't notice the mess ^^ I'm new to programming
public function mudar_doc1(Request $request) {
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
$rules = array('image' => 'required|image',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return Redirect::to('userp')->withInput()->withErrors($validator);
} else {
// checking file is valid.
if (Input::file('image')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
$extensoes = array("png", "jpeg", "jpg", "gif");
$resVal = in_array($extension, $extensoes);
if ($resVal) {
} else {
Session::flash('error', 'O upload não foi realizado com sucesso.');
return Redirect::to('userp');
}
$fileName = rand(11111, 99999) . '.' . $extension; // renameing image
Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
$doc1 = asset($destinationPath . '/' . $fileName);
User::where('id', \Auth::user()->id)->update(['doc1' => $doc1]);
// sending back with message
Session::flash('success', 'ID Card Front Successfully Added!');
\App\RegistroAtividade::addAtividade('Cartao ID Frente');
return Redirect::to('userp');
} else {
// sending back with error message.
Session::flash('error', 'O upload não foi realizado com sucesso.');
return Redirect::to('userp');
}
}
}
<tbody>
#foreach($allAtividades as $atividade)
<tr>
<td>{{$atividade['id']}}</td>
<td>{{$atividade->getUser()->name}}</td>
<td>{{$atividade['ip']}}</td>
<td>{{$atividade['description']}}</td>
<td>{{$atividade['created_at']}}</td>
</tr>
</tbody>
#endforeach
I don't see much reference in your code for the Image / controller / view or data, please update your question and i will update this answer along
Some important note I would like to make
I would suggest you spare some time reading about the Eloquent Relations
Then you can create the Actividade Eloquent if you don't have it already
In Actividade Eloquent you can assign a user relations like so
Class Actividade {
//...
public function user(){
return $this->belongsTo(App\User::class, 'user_id');
}
}
The user method here will return the user by using the user_id column in the actividade table [if you have it set up correctly already], that will make it easier to fetch the user for activities $actividade->user->name, instead of $actividade->getUser()->name;
following this approach you can have an ImagesEloquent class having activities method which is relational just like activities having users and users having activities:
using this approach (skeleton) would be as easy as this:
#foreach(Image::find(1)->activities as $_activity){
<td><img src="{{Image::find(1)->filename}}"/></td> <!-- just an example here -->
<td>{{$_activity->id}}</td>
<td>{{$_activity->user->name}}</td>
<td>{{$_activity->ip}}</td>
<td>{{$_activity->description}}</td>
<td>{{$_activity->created_at}}</td>
#endforeach
You fetch the Image, you can fetch it's activities, and then each activity has users
It will take a bit of time (an hour or so) to learn about this, but will save you hundreds of hours in the future and get you a way cleaner code, i thought to suggest that.
Related
I'm trying to make a POST request with params in terms of a file upload and user text upon user clicking Submit. However, I keep getting a failed response via the dd(); (which's coming from the API endpoint I've received) for some reason even though I get the file upload success message defined by the flash. What am I doing wrong in my controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Zttp\Zttp;
class FileUploadController extends Controller {
public function index(){
return view('view/index');
}
public function uploadFile(Request $request) {
$userText = $request->input('userText'); // grabbing text area input that user inputs
if ($request->input('submit') != null ){
$file = $request->file('file'); // file user wants to upload
// File Details
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileSize = $file->getSize();
// Valid File Extensions
$valid_extension = ["jpg", "jpeg", "png", "bmp"];
// 10MB in Bytes
$maxFileSize = 10485760;
// Check file extension
if(in_array(strtolower($extension),$valid_extension)) {
// Check file size
if($fileSize <= $maxFileSize){
$request->session()->flash('message','Upload Successful.');
$response = Zttp::post("https://myendpoint.com/upload.php", [
'one' => 'some text',
'two', 'some other text',
'three' => $filename,
'four' => $userText
]);
$responseJson = $response->json(); // parses json response into an array for you
dd($responseJson);
} else {
$request->session()->flash('message','File too large. File must be less than 2MB.');
}
} else {
$request->session()->flash('message','Invalid File Extension.');
}
}
// Redirect to index
return redirect()->action('FileUploadController#index');
}
}
The question is a bit of a red herring. It's not your controller giving the failed response. Whatever's going on at the endpoint is living in a seperate request and the error lives there.
Additionally – your flash message declares the upload successful before your controller posts anything to your endpoint.
<?php
// ...
$request->session()->flash('message','Upload Successful.');
$response = Zttp::post("https://myendpoint.com/upload.php", [/* */]);
I reccommend you parse the $response more thoroughly and only set the flash message if the response code is 2XX.
Any debugging re: a failed response at that endpoint will rely on more info, including the response itself, and the nature of the endpoint. (Is it also yours? A third party API?)
I need to send an image to server via an ajax request and it gets through just fine
and in my controller I can just use $_FILES["image"] to do stuff to it.
But I need to validate the image before I save it.
And in the Yii this can be achieved by doing something like this
$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}
But the problem is I don't have a $model, all I have is $_FILES["image"], now what should I put instead of the $model???
is there any other way where I can validate and save files without creating a model and just by Using $_FILES["image"]?
thanks for this awesome community... :)
Exists many ways how you can do upload. I want offer to you one of them.
1.You need to create model for your images.
class Image extends CActiveRecord {
//method where need to specify validation rules
public function rules()
{
return [
['filename', 'length', 'max' => 40],
//other rules
];
}
//this function allow to upload file
public function doUpload($insName)
{
$file = CUploadedFile::getInstanceByName($insName);
if ($file) {
$file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
} else {
$this->addError('Please, select at least one file'); // for example
}
}
}
2.Now, need to create controller, where you will do all actions.
class ImageController extends CController {
public function actionUpload()
{
$model = new Image();
if (Yii::app()->request->getPost('upload')) {
$model->filename = 'set filename';
$insName = 'image'; //if you try to upload from $_FILES['image']
if ($model->validate() && $model->doUpload($insName)) {
//upload is successful
} else {
//do something with errors
$errors = $model->getErrors();
}
}
}
}
Creating a model might be overkill in some instances.
The $_FILE supervariable is part of the HTTP mechanism.
You can handle the copy by using the native PHP function move_uploaded_file()
$fileName = "/uploads/".myimage.jpg";
unlink($fileName);
move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);
However, you lose the niceties of using a library that provides additional functionality and checks (eg file type and file size limitations).
I am adding the ability to edit an image that is already uploaded on a shopping cart app I am building. I am able to upload an image fine. I am also able to edit every field perfectly except for the image file upload.
I have tried using the same code I have in the upload function to basically upload another image over the existing one but it does not work and throws an error
Call to a member function getClientOriginalExtension() on a non-object
I am using the Laravel framework with intervention and went to the main site of intervention and it does not show an update or edit method. It just shows a delete method.
I need some help in figuring out how to update the image in my postEdit function.
I really have tried everything I know and have researched this with google and cannot figure this out.
My problem lies in this line of code:
File::update('public/'.$product->image);
Thank you for the right direction.
Here is the image upload function (which works perfect)
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/products/' . $filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
Here is the edit image upload function which I cannot get to work.
public function postEdit() {
$product = Product::find(Input::get('id'));
if ($product) {
File::update('public/'.$product->image);
$product->update(Input::all());
return Redirect::to('admin/products/index')
->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong, please try again');
}
First there is no method for the File facade called update.
You have to reprocess the image to update it.
Secondly, the error is being thrown from the upload. This could be because the image is not being sent through the form properly.
Make sure you have files attribute on your form open.
{{ Form::open(array('route'=> array('aroute'),'method' => 'post', 'files' => true)) }}
If your file is still not being sent check your php.ini setting as the file size of the image could be greater of that set in the post_max_size or upload_max_filesize to a value greater than that size.
Also the change the line;
$path = public_path('img/products/' . $filename);
to
$path = public_path() . 'img/products/' . $filename;
And to edit the image with intervention you need to save the file.
Use;
$image->move($path);
then you can do;
Image::make($path)->resize(468, 249)->save($path);
I have setup a repository to create a new resident.
<?php namespace Crescent\Repos;
interface ResidentRepository {
public function create($input);
}
Then in my controller I have, which uses the intervention image class to resize an image and it uploads correctly to the directory, but how can I save the name of the file to the DB using this repo?
public function store()
{
if (Input::hasFile('photo')){
$res = new Residents;
$file = Input::file('photo');
$name = $file->getClientOriginalName();
$input = Input::all();
$image = Image::make(Input::file('photo')->getRealPath())->resize(200, 200);
$image->save(public_path() . '/uploads/residents/' . $input['photo']->getClientOriginalName());
$res->photo = $name; // This doesn't work
}
$this->resident->create(Input::all());
}
Everything else works all the data, but the image isn't storing the name just showing some temp dir/name like /tmp/phpIX7KcY
I see that you have done $res = new Residents; and $res->photo = $name; but you haven't done $res->save(); which would have saved the name to the table corresponding to Residents. Also since you haven't added anything else to $res, only the photo would be saved.
Replace the code in your controller with the following:
public function store()
{
$input = Input::all();
if (Input::hasFile('photo')){
$file = Input::file('photo');
$name = $file->getClientOriginalName();
$image = Image::make(Input::file('photo')->getRealPath())->resize(200, 200);
$image->save(public_path() . '/uploads/residents/' . $input['photo']->getClientOriginalName());
$input['photo'] = $name;
}
$this->resident->create($input);
}
If in your code $this->resident->create(Input::all()); saves all data properly except the photo, it is because by passing Input::all() you're saving everything exactly as it was received from the client and the filename received from the resizing operation isn't present in Input::all(). By assigning Input::all() to the variable $input and doing $input['photo'] = $name;, the location of the file on the server is stored instead of the location on the client. So, by doing $this->resident->create($input);, the location on the server is stored along with other data received from the client.
this might be a bit of a novice question and here is my situation:
i have a upload form for uploading images. and in my editAction i do:
if ($request->isPost()) {
if (isset($_POST['upload_picture']) && $formImageUpload->isValid($_POST)) {
//here i will add the picture name to my database and save the file to the disk.
}
}
$picVal = $this->getmainPic(); // here i do a simple fetch all and get the picture that was just uploaded
$this->view->imagepath = $picVal;
what happens is that the newly uploaded picture doesn't show. I checked the database and the dick and the file is there.
im thinking the problem might be the order of the requests or something similar.
any ideas?
edit: another thing is that in order to make the new image come up i have to do a SHIFT+F5 and not only press the browser refresh button
edit2: more code
i first call the upload to disk function then if that returns success addthe file to the database
$x = $this->uploadToDiskMulty($talentFolderPath, $filename)
if($x == 'success'){
$model->create($data);
}
the upload function
public function uploadToDiskMulty($talentFolderPath, $filename)
{
// create the transfer adapter
// note that setDestiation is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($talentFolderPath)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
If the picture only appears when you do SHIFT+F5 that means it's a caching problem. Your browser doesn't fetch the image when you upload it. Do you use the same file name?