Laravel 4, delete image within a post method / possible? - php

I am trying to delete an old user image, if the user updates his profile picture. I am using Laravel 4.1 and a resourceful UsersController.
Updating the picture works perfectly fine. A new one is saved in my folder and the file nave is overwritten in the database. However, I would like to delete the old image. Therefore I have the following code, which works fine if I use it on an empty page with route get 'test' for example
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
Everytime I try to implement this into the process of updating the image, the old one is not deleted. I have already in mind that I have to delete the old one before overwriting the file name.
Does this have to do anything with the POST method the Controller uses for updating? How could I fix it?
public function update($id){
$validation = Validator::make(
Input::all(), [
'name'=>'required',
'surname'=>'required',
'email'=>'required',
'email' => 'email']);
if($validation->fails()){
return Redirect::to(
'dashboard#profile'
)->withInput()->withErrors(
$validation->messages());
}
$user = User::find($id);
$user->name = Input::get('name');
$user->surname = Input::get('surname');
$user->email = Input::get('email');
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
$imageFile = Input::file('profile_picture_update');
$newprofile_picture = Image::make(
$imageFile->getRealPath()
)->resize(400, null, true)->crop(400, 400);
$name = time() . '-' .
Input::get('name') .
'-' . Input::get('surname') .
'.' . $imageFile->getClientOriginalExtension();
// $name = time() . '-' . $profile_picture->getClientOriginalName();
// Below the profile_picture variable is overrridden.
$newprofile_picture = $newprofile_picture->save(
public_path().'/img/profile_pictures/users/'.$name
);
$user->profile_picture = $name;
$user->save();
return Redirect::to(
'dashboard#profile'
)->with(
'updatemessage', 'Yep! Deine Ă„nderungen wurden gespeichert.'
);
}

why don't you use the User model you just retrieved to get the old image?
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
replace it with
if (Input::hasFile('profile_picture_update')) {
$oldimage = $user->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}

I found a way to do this by creating a helper function an then calling the helper function in the controller method.
http://laravel.com/docs/helpers

Related

How can I add media files in laravel?

A user can register/sign up as either a Job Seeker or an Employer. If he is a Job Seeker, he can create a profile on the create profile page. On the form their are 4 inputs with the file type, among other inputs.
See screenshot below.
I have a Table called job_seeker_profiles, there are several columns in there, but only these 4 are relevant to my issue.
resume_id, video_one_id, video_two_id, video_three_id
I also have 2 Tables, Resumes and Videos, each have one column called 'file'.
This is working, the file paths are being inserted into the database.
In my public folder, I created 2 directories resumes and videos. This is where I want to store the files. This part is also working, when I upload a resume only (No Videos, they are optional) and click Create Profile, The file appears in the /resumes folder within my public folder.
The problem is, in the resume_id column in the job_seeker_profiles Table, I get this value inserted into my database "/Applications/XAMPP/xamppfiles/temp/phpx6Dmr" instead of the id of the file from the Resumes Table.
I think maybe it's a problem with my relationships?
Here is my code.
AdminJobSeekerProfilecontroller.php file:
public function store(JobSeekerCreateRequest $request)
{
if($file = $request->file('resume_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('resumes', $name);
$resume = Resume::create(['file'=>$name]);
$input['resume_id'] = $resume->id;
}
$input = $request->all();
if($file = $request->file('video_one_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input2['video_one_id'] = $video->id;
}
$input2 = $request->all();
if($file = $request->file('video_two_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input3['video_two_id'] = $video->id;
}
$input3 = $request->all();
if($file = $request->file('video_three_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input4['video_three_id'] = $video->id;
}
$input4 = $request->all();
JobSeekerProfile::create($input, $input2, $input3, $input4);
return redirect('/admin/job-seeker/profile/create');
}
Resume.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Resume extends Model
{
protected $uploads = '/resumes/';
protected $fillable = ['file'];
//create an accessor
public function getFileAttribute($resumes){
return $this->uploads . $resumes;
}
}
JobSeekerProfile.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class JobSeekerProfile extends Model
{
protected $dates = ['date_of_birth'];
protected $fillable = [
'user_id',
'photo_id',
'resume_id',
'video_one_id',
'video_two_id',
'video_three_id',
'first_name',
'last_name',
'email',
'full_or_part_time',
'additional_skills',
'file'
];
public function user(){
return $this->belongsTo('App\User');
}
public function resume(){
return $this->belongsTo('App\Resume');
}
public function video(){
return $this->belongsTo('App\Video');
}
}
On a side note, I know I should store the video files on something like amazon s3, but I want to get it working this way for now. And if you have any recommendations for Laravel and hosting files on a cloud based system that would be great as well.
Thank you Tpojka. This worked for me now:
$input = $request->all();
$user = Auth::user();
if($file = $request->file('resume_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('resumes', $name);
$resume = Resume::create(['file'=>$name]);
$input['resume_id'] = $resume->id;
}
$user->jobseekerprofile()->create($input);
return redirect('/admin/job-seeker/profile/create');

Having a problem with a pivot table on Laravel

I have a form with two pivot tables. One of them works just fine but I can't seem to be making the second one work despite them being quite similar. The one not working is for an image table called 'photos' and the form upload in called 'releases'. I called the pivot table 'photo_releases' with the 'photo_id' and a 'release_id' field.
DB Pivot Table
here is the release Modal
class Release extends Model
{
public function photos()
{
return $this->belongsToMany('App\Photo', 'photo_releases', 'release_id', 'photo_id');
}
}
and the photo modal
class Photo extends Model
{
public function releases()
{
return $this->belongsToMany('App\Release', 'photo_releases', 'photo_id', 'release_id');
}
}
and the ReleaseController
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01')) {
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file->getClientOriginalName());
$name = time() . 'photo_01' . $file_name;
$file->move('images', $name);
$input['photo_01'] = $name;
$photo = new Photo();
$photo->url = $input['photo_01'];
$photo->save();
}
$release = Release::create($request->except('release_id'));
dd($request->except('release_id'), $request->get('photo_id', []), $request->get('artiste_id', []));
$release->photos()->attach($request->get('photo_id', []));
$release->artistes()->attach($request->get('artiste_id', []));
return redirect('/admin06000/releases');
}
There is two pivot tables being used in this function. the one using
"$release->artistes()->attach($request->get('artiste_id', []));"
is working correctly but the photos is not. The url is being logged in the correct DB and the image is uploading fine, but the pivot table is not being updated. If anyone could help it would be greatly appriciated.
try This if you need some select in relation ship change
with('photos')
to
with(['photos'=>function($query){$query->where(....)->get();}])...
use Image;
use Illuminate\Support\Facades\Input;
...
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01'))
{
$image= Input::file('photo_01');
$name = time().'photo_01'.'.'.$image->getClientOriginalExtension();
$path=public_path('/YourPath/'.$name);
Image::make($image->getRealPath())->save($path);
$photo = new Photo();
$photo->url = '/YourPath/'.$name;
$photo->save();
}
$release = Release::create
([
'release_field'=>$amount,
'release_field2'=>$amount2,
....
]);
$release->with('photos')->with(artistes)->get();
}```

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' ];

Laravel 5.2 - Intervation Image resize

i'm tryng to resize image of user profile, but i have this error:
NotReadableException in Decoder.php line 96: Unable to init from given
binary data.
MY CONTROLLER
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
// if i insert here: retur $user_id it return: 1.jpg it work well,
// my form work well, before i tryed to upload without resize and it work well.
// i want save image uploaded with id user and extention
// here i'm tryng to resize it, i installed intervation and inserted class
$img = Image::make('images/users',$user_id);
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
}else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
You're trying to supply two arguments to Image::make(), but it should only be given one. I think you might want to do e.g. Image::make('images/users/'.$user_id) instead? Or whatever your full path to the file is.
Try this - I think you were trying to create an Image from a text string, or possibly something that doesn't exist. I don't have my code editor in front of me, so I can't test, let me know what you get?
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
$img = Image::make($request->file('image'));
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
} else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
$base=base64_decode($request['image']);
$img = Image::make($base)->save($path);
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
} else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
This will definitely solve your issue..

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