Hi everyone I want to add a file, not an image. There are different types of files in laravel. With the file I need to upload the user id to the database but I don't know how to store it in controller, here are my scripts:
Controller.php:
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
$path = $request->image->store('storage/uploads','public');
return back();
}
upload.blade.php
{!! Form::open(['action' => ['FileController#upload', $client->id, 'files' => 'true']]) !!}
{!!Form::file('image') !!}
{!!Form::submit('Upload File') !!}
{!! Form::close() !!}
and web.php
Route::post('upload/{id}/', 'FileController#uploaded');
Can you explain me how to do it correctly?
Just change your upload.blade.php as
{!! Form::open(['route' => ['file.upload', $client->id, 'files' => 'true']]) !!}
{!!Form::file('image') !!}
{!!Form::submit('Upload File') !!}
{!! Form::close() !!}
and your web.php to
Route::post('upload/{id}/', 'FileController#uploaded')->name('file.upload');
I little confuse about your question. But I hope my answer can help you with your problem.
First Answer:
If you want to save the file in database I think you can save it with store the file path only in another table, we can call it user_files with this structure:
user_files
| id | user_id | file |
| 1 | 2 | /home/name/file
And the relations between this table and clients table is oneToMany.
so in your Client.php will be have this method:
Client.php
public function files() {
return $this->hasMany(File::class, 'user_id');
}
and your File.php will be have this method:
File.php
public function client() {
return $this()->belongsTo(Client::class, 'user_id');
}
After that, now we move in controller that handle upload method. We should save the file with associate the data from client.
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
// If you need to upload file not only image, I think you should use $request->file() method;
$file = $request->file('file');
// And then we save the name use this method, maybe you want to save it with change the name and include the user_id
$name = 'User' . '#' . $client->id . '.' . $file->getClientOriginalExtension();
// It will make the file named 'User#2.doc'
// After that we move the file in 'uploads' directory or other public directory you want.
$file->move(public_path('uploads'), $name);
$newFile = new File;
$newFile->file = public_path('uploads') . '/' . $name;
$newFile->client()->associate($client);
$newFile->save();
return back();
}
That if you want to save the file in database with user_id as identifier, and also you can access it as usual, like if you want to access the image file:
<img src="{{$newFile->file}}" />
Second Answer
But if you only want to save the file with the name of user_id you can use only the method in controller:
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
// If you need to upload file not only image, I think you should use $request->file() method;
$file = $request->file('file');
// And then we save the name use this method, maybe you want to save it with change the name and include the user_id
$name = 'User' . '#' . $client->id . '.' . $file->getClientOriginalExtension();
// It will make the file named 'User#2.doc'
// After that we move the file in 'uploads' directory or other public directory you want.
$file->move(public_path('uploads'), $name);
return back();
}
Related
i am trying to update the image of profil ,because to user at the beginning it creates account without image, after it goes the update, so i store the image in root /aswakfolder/public/storage/profiles and i insert image link in db profiles/nameimage.jpeg, i created a function in helpers.php file to display the image its work very will, the problem here is that I do not understand the helpers function, and it does not meet my needs, my need is when image upload and exists it displays my image if not it displays image not-found.jpeg,in my case it always displays not-found.jpeg.
stock image in my folder, and url image insert in db very well.
UsersController.php
public function update(Request $request, $id)
{
$user=User::find($id);
if($request->hasFile('image'))
{
$image = $request->file('image');
$path = $request->image->store('profiles');
$user->image = $path;
}
$request->image = $user->image;
$user->id = Auth::user()->id;
$user->update([
$user->name => $request->name,
$user->email => $request->email,
$user->telephone => $request->telephone,
$user->daten => $request->daten,
$user->country_id=> $request->country_id,
$user->state_id => $request->state_id,
$user->city_id => $request->city_id,
$user->image => $request->image,
]);
session()->flash('success', 'user updated successfully !!');
return redirect('users');
}
helpers.php
function productImage($path)
{
return $path && file_exists('/aswakfolder/public/storage/'.$path) ? asset('/aswakfolder/public/storage/'.$path) : asset('/aswakfolder/public/storage/not-found.jpg');
}
index.blade.php
<div class="inner" style="background-image: url({{ asset(productImage($users->image)) }})">
Make sure you run the commend php artisan storage:link to create the shortcurt on public/ folder.
Documentation
i have been trying to update photos in an album but i cant get it right. i know that i need to get the album id of the photos that i want to update but i cannot get the right logic for the request.
this is the error am getting whenever i request for an update
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'album_id' cannot be null (SQL: update `photos` set `album_id` = , `photo` = IMG-20190527-WA0001_1570703623.jpg, `size` = 275807, `updated_at` = 2019-10-10 10:33:44 where `id` = 197)
the photos model for the application is as shown below
class Photos extends Model
{
protected $fillable = array('album_id', 'description', 'photo', 'title', 'size');
public function album(){
return $this->belongsTo('App\Album');
}
}
this is what i have tried for the update logic in the photosController. i have tried to request for the album id but it does not seem to work
public function edit($id){
$photo = Photos::find($id);
return view('photos/edit')->with('photo', $photo);
}
public function update(Request $request, $id){
$this->validate($request, [
'photo' => 'required | max:15000'
]);
$path = [];
//get filename with extension
$filenameWithExt = $request->file('photo')->getClientOriginalName();
//get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $request->file('photo')->getClientOriginalExtension();
//create new file name
$filenameToStore = $filename.'_'.time().'.'.$extension;
//get file size
$filesize = $request->file('photo')->getClientSize();
$path = $request->file('photo')->storeAs('public/photos'.$request->input('album_id'), $filenameToStore);
$photo = Photos::find($id);
$photo->album_id = $request->input('album_id');
$photo->size = $filesize;
$photo->photo = $filenameToStore;
$photo->save();
return $path;
}
each time i return the path for the photo am updating there is no id for the photo. only happens when i omit the save method
public/photos//IMG-20190527-WA0001_1570706571.jpg
photo edit php view code
{!!Form::open(['action' => ['PhotosController#update', $photo->id], 'method' => 'POST', 'enctype' => 'multipart/form-data'])!!}
{{Form::file('photo')}}
{{Form::hidden('_method','PUT')}}
{{Form::submit('submit')}}
{!! Form::close() !!}
database model for photos table
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('album_id');
$table->string('photo');
$table->string('size');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('photos');
}
help would be appreciated
The error is at this line
$photo->album_id = $request->input('album_id');
You don't have an input in your form with the name album_id
You can either create a hidden one and assign it the value
{!!Form::open(['action' => ['PhotosController#update', $photo->id], 'method' => 'POST', 'enctype' => 'multipart/form-data'])!!}
{{Form::file('photo')}}
{{Form::hidden('_method','PUT')}}
{{-- Here --}}
{{Form::hidden('album_id', $photo->album->id)}}
{{Form::submit('submit')}}
{!! Form::close() !!}
or get it from the relationship like so
$photo->album_id = $photo->album->id;
Note that you're also using that null|empty value here
$path = $request->file('photo')
->storeAs('public/photos'.$request->input('album_id'), $filenameToStore);
So make sure to update that too
Hope this helps
My user uploads a profile picture which is stored in storage/profile_picture/user1.png. I use Filesystem and Storage classes to do so.
To retrieve the image I use {!! Html::image(route('profile.thumbnail', $user->profilepic_filename), "Your Picture Here", ['class'=>'img-responsive']) !!}
In my Controller I have
public function thumbnail($filename)
{
$user = User::where('profilepicture_filename', '=', $filename)->firstOrFail();
$file = Storage::disk('local_profile')->get($user->profilepicture_filename);
//$file = URL::asset('/images/default_profilepicture.png'); //doesn't work
return (new Response($file, 200))->header('Content-Type', $mime);
}
}
I want to get a default image if the profile picture is not found or not uploaded. How can I do so?
Thanks,
K
For something like this I would just override the accessor (aka getter) on your User model.
http://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators
Any database column, such as profilepicture_filename can be manipulated after it's retrieved using a get___Attribute method, where ___ is the column name in Camel Case
class User
{
/**
* #return string
*/
public function getProfilepictureFilenameAttribute()
{
if (! $this->attributes['profilepicture_filename'])) {
return '/images/default_profilepicture.png';
}
return $this->attributes['profilepicture_filename'];
}
}
Now you simply have to do
<img src="{{ asset($user->profilepicture_filename) }}">
And it will display either their picture or the default if they don't have one. You no longer need the thumbnail route.
you could just do in you view:
#if(!file_exist($file->name))
<img src="/path/to/default.png">
#else
<img src="{{$file->name}}">
#endif
or in your controller:
if(!$file)
{
$file = '.../default/blah.png';
}
So, I am trying to battle the old file upload inside of the Laravel framework but getting a bit lost. I have managed to get the upload to work so the file uploads and saved into an assets folder with a random string name.
This is the form:
<form action="{{ URL::route('account-upload') }}" method="post">
{{ Form::label('file','Upload File') }}
{{ Form::file('file') }}
<br />
{{ Form::submit('Upload') }}
{{ Form::token() }}
</form>
This is the Route:
Route::get('/account/upload', array(
'as' => 'account-upload',
'uses' => 'AccountController#getUpload'
));
Route::post('/account/upload', function(){
if (Input::hasFile('file')){
$dest = 'assets/uploads/';
$name = str_random(6).'_'. Input::file('file')->getClientOriginalName();
Input::file('file')->move($dest,$name);
return Redirect::to('/account/upload')
->withGlobal('Your image has been uploaded');
}
});
this is the method inside AccountController:
public function getUpload(){
return View::make('account.upload');
}
public function postUpload() {
$user = User::find(Auth::id());
$user->image = Input::get('file');
}
I am now trying to enable that to push the string name into the database and also be associated with the user who uploaded it and show as their profile image? Ay pointers would be great!
I have created a row inside of the database named 'file' with the type of text....I am not sure on this point of how to store and view the image.
try this
// the view
{{ Form::open(['route' => 'account-upload', 'files' => true]) }}
{{ Form::label('file','Upload File') }}
{{ Form::file('file') }}
<br />
{{ Form::submit('Upload') }}
{{ Form::close() }}
// route.php
Route::get('/account/upload', 'AccountController#upload');
Route::post('/account/upload', [
'as' => 'account-upload',
'uses' => 'AccountController#store'
]);
// AccountController.php
class AccountController extends BaseController {
public function upload(){
return View::make('account.upload');
}
public function store() {
if (Input::hasFile('file')){
$file = Input::file('file');
$dest = public_path().'/assets/uploads/';
$name = str_random(6).'_'. $file->getClientOriginalName();
$file->move($dest,$name);
$user = User::find(Auth::id());
$user->image = $name;
$user->save();
return Redirect::back()
->withGlobal('Your image has been uploaded');
}
}
}
// and to display the img on the view
<img src="assets/upload/{{Auth::user()->image}}"/>
In order to upload a file, you'll need enctype="multipart/form-data" as an attribute on the <form> element.
If you're using the Form::open() method, you can just pass "files" => true here, but this should allow you to actually use Input::file() correctly.
Next, when actually dealing with the file, you'll need to use something like storage_path() or public_path() and give an absolute path to the file's destination when moving it.
And a tip: you fetch an authed user's model by calling Auth::user().
I'm trying to learn to an process image form that uploads images to a database and lets users view the image on the website, this is done using Laravel 4. I must have some sort of bug, because the view doesn't have any errors, but when I select an image to upload and hit the "save" button on my form, nothing happens other than it looks like the form has been refreshed because the file is gone.
Routes
// This is for the get event of the index page
Route::get('/', array(
'as' => 'index_page',
'uses' => 'ImageController#getIndex'
));
// This is for the post event of the index page
Route::post('/', array(
'as' => 'index_page_post',
'before' => 'csrf',
'uses' => 'ImageController#postIndex'
));
ImageController.php
class ImageController extends BaseController {
public function getIndex()
{
// Let's first load the form view
return View::make('tpl.index');
}
public function postIndex()
{
// Let's validate the form first with the rules which are set at the model
$input = Input::all();
$rules = Photo::$upload_rules;
$validation = Validator::make($input, $rules);
// If the validation fails, we redirect the user to the index page, with errors
if ($validation->passes()) {
// If the validation passes, we upload the image to the database and process it
$image = Input::file('image');
// This is the original uploaded client name of the image
$filename = $image->getClientOriginalName();
// Because Symfony API does not provide filename
// without extension, we will be using raw PHP here
$filename = pathinfo($filename, PATHINFO_FILENAME);
// We should salt and make an url-friendly version of the file
$fullname = Str::slug(Str::random(8) . $filename) . '.' .
$image->getClientOriginalExtension();
// We upload the image first to the upload folder, then
// get make a thumbnail from the uploaded image
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
// If the file is now uploaded we show a success message
// otherwise, we show an error
if ($upload) {
// image is now uploaded, we first need to add column to the database
$insert_id = DB::table('photos')->insertGetId(
array(
'title' => Input::get('title'),
'image' => $fullname
)
);
// Now we redirect to the image's permalink
return Redirect::to(URL::to('snatch/'.$insert_id))
->with('success', 'Your image is uploaded successfully!');
}
else {
// Image cannot be uploaded
return Redirect::to('/')->withInput()
->with('error', 'Sorry, the image could not be uploaded.');
}
}
else {
return Redirect::to('/')
->withInput()
->withErrors($validation);
}
}
Image Model
class Photo extends Eloquent {
// the variable that sets the table name
protected $table = 'photos';
// the variable that sets the table name
protected $fillable = array('title', 'image');
// the timestamps enabled
public $timestamps = true;
// Rules of the image upload form
public static $upload_rules = array(
'title' => 'required|min:3',
'image' => 'required|image'
);
}
The view for the form
#extends('frontend_master')
#section('content')
{{ Form::open(array('url' => '/', 'files' => true )) }}
{{ Form::text('title', '', array(
'placeholder' => 'Please insert your title here')) }}
{{ Form::file('image') }}
{{ Form::submit('save', array('name' => 'send')) }}
{{ Form::close() }}
#stop
Let me know if you can find any bugs, I'm pretty sure something must be going wrong in my ImageController#postIndex
Thanks for any insights
2 things you need to check out.
1st off, once you updated your composer.json to include the Intervention/Image package. you should run composer dump-autoload to refresh the autoload file.
2ndly, there's a logical error in your controller.
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
should be
Image::make(Config::get('image.image_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
because you've already moved the image file to image_folder with the code below:
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Hope this helps.