Display stored image in Laravel - php

I am new to this, I have stored image in public/storage but I can't figure out how to display it.
I have this function in UploadController:
public function store(request $request)
{
if ($request->hasFile('file')) {
$request->file('file');
return $request->file->store('public');
}
return 'No file selected';
}
This in web.php:
Route::get('/', 'UploadController#index');
Route::post('store', 'UploadController#store');
And this in welcome.blade.php:
{!! Form::open(['url' => '/store', 'method' => 'post', 'files' => true]) !!}
File name:
{!! Form::text('episode') !!}
{!! Form::file('file'); !!}
{!! Form::submit('Upload File') !!}
{!! Form::token() !!}
{!! Form::close() !!}
It displays name of the saved file in /store
Can anyone please give me an advice how to display the image?

'$request->file->store('public');' will return a path to your saved file with a unique name so save the returned path in your database or where ever like below:
$path = $request->file->store('public');
Now $path variable contains path (url) to your saved file.
And use this path to display your stored image.

Related

always return null while uploading file to laravel 7

I'm having an issue while uploading file to laravel either its pdf or image always return to null
This is the View
{!! Form::open(['action' => 'TransactionInController#store', 'method' => 'POST', 'autocomplete' => 'off',
'class' => 'form-horizontal', 'enctype' => 'multipart/form-data']) !!}
<div class="row">
{{ Form::label('Device Document', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="col-sm-7">
{{ Form::file('device_document') }}
<p style="color: red;">#error('device_document') {{ $message }} #enderror</p>
</div>
</div>
{!! Form::close() !!}
and this is the Controller i use
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$imageName = $request->input('device_document');
$request->image->move(public_path('document-image'), $imageName);
$transactionsin->save();
return redirect('/transactionsin');
}
i know its been asked before and i already try several way to upload file this error.
This is the error message i get while running the code
Call to a member function move() on null
but if i change the code in controller into something more simple like this
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$transactionsin->device_document = $request->input('device_document');
$transactionsin->save();
return redirect('/transactionsin');
}
it will not return any error message but it will saved as null in the database.
Use $request->file('device_document') instead of input method to catch a file.
If you would like to get original name of the uploaded file, you may do so using the getClientOriginalName() method
Try this :
public function store(Request $request)
{
$this->validate($request, [
'device_document' => 'nullable|max:8192|mimes:pdf'
]);
$transactionsin = new TransactionIn;
$imageName = $request->file('device_document');
$imageName->move(public_path('document-image'), $imageName->getClientOriginalName());
$transactionsin->device_document = $request->file('device_document')->getClientOriginalName();
$transactionsin->save();
return redirect('/transactionsin');
}
See the official documentation here
you can access file using file() method not input method and after upload image to get image path using asset() function like this below code
$transactionsin = new TransactionIn;
$image= $request->file('device_condition');
//upload imaage
$image->move(public_path('document-image'), $image->getClientOriginalExtension());
//asset() function use store path
$transactionsin->device_document = asset('document-image/'.$image->getClientOriginalExtension());
$transactionsin->save();

'multipart/form-data' not working

I'm using Laravel and trying to build a gallery, i'm testing the upload of a file but i when i attach a file and click submit i can't get a positive outcome using the test set up. The code is below
GalleryController
// Store Gallery
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description', '');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if($cover_image){
die ('YES');
} else {
die ('NO');
}
}
The form is set up as follows
{!! Form::open(array('action' => 'GalleryController#store', 'enctype' => 'multipart/form-data')) !!}
{!! Form::label ('name', 'Name') !!}
{!! Form::text ('name', $value = null, $attributes = ['placeholder' => 'Gallery Name', 'name' => 'name']) !!}
{!! Form::label ('description', 'Description') !!}
{!! Form::text ('name', $value = null, $attributes = ['placeholder' => 'Gallery Description', 'name' => 'Description']) !!}
{!! Form::label ('cover_image', 'Cover Image') !!}
{!! Form::file('cover_image') !!}
{!! Form::submit ('Submit', $attributes = ['class' => 'button']) !!}
{!! Form::close() !!}
Any help is appreciated
Thanks
Your form looks correct, it is likely your controller where you are retrieving the uploaded file.
As per the docs, to retrieve an uploaded file you should use $request->file():
$request->file('cover_image');
That link to the docs above also goes on to explain how you can check the file properly and store the file.
//use input facades.
use File;
use Illuminate\Support\Facades\Input;
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description', '');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if(Input::hasFile('cover_image'){
die ('YES');
}
else {
die ('NO');
}
}

laravel 5 won't delete files from storage section

when I try to delete specific file trough my controller I get an error
Sorry, the page you are looking for could not be found.
NotFoundHttpException
This is my controller:
public function destroyFile($file_name)
{
$file = storage_path('documents').'/'.$file_name;
Storage::delete($file);
return redirect('/documents');
}
My route:
Route::delete('documents/{file}','FilesController#destroyFile');
And my view:
{!! Form::open(['method' => 'DELETE', 'action' => ['FilesController#destroyFile', $file->name] ]) !!}
{!! Form::hidden('_method', 'DELETE') !!}
{!! Form::token() !!}
{!! Form::submit(trans('buttons.del-cat'),['class'=>'btn btn-danger user-delete push-right']) !!}
{!! Form::close() !!}
I had the same problem, everything was set right but it still didn't work.
Instead of Storage::delete() I used File::delete(), that fixed it.
Hope this works!
public function images(Request $request,$id){
$user_id=$request->session()->get('user_id');
$data=DB::table('company_images')->where('id',$id)->first();
//deleteing the image from database and server
DB::table('company_images')->where('id', '=', $id)->delete();
//delete the image form the server
$path=public_path("/assets/img/company/$data->image");
unlink($path);
return redirect("/company/$user_id/add_details")->with('delete','delete');
}
this is function i used to delete company images using unlink($path) this works well with me also the big note:you should write carefully the path to file you delete.
You must set public in filesystem.php :
'default' => env('FILESYSTEM_DRIVER', 'public')
instead of :
'default' => env('FILESYSTEM_DRIVER', 'local')
change local to public.

How to customize a field of the model before storing in database

I have a model like this :
class Article extends Model {
protected $fillable = [
'title',
'body',
'img_profile', // store name of image
];
}
And a controller like this:
public function store(ArticleRequest $request){
$article = Auth::user()->articles()->create($request->all());
return redirect('articles');
}
And a form like this:
{!! Form::model($article = new \App\Article,['url' => 'articles','files' => true ]) !!}
{!! Form::text('title', null ) !!}
{!! Form::textarea('body', null) !!}
{!! Form::file ('img_profile', '') !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
When I submit the form, the img_profile field is stored default cached file which is /private/var/tmp/phpceBMP2.But I just want to update file_name in img_profile.
How can I change the value of the img_profile request before storing it in database?
You should use mutator for Article model this way:
public function setImgProfileAttribute($value)
{
$this->attributes['img_profile'] = '/private/var/tmp/phpceBMP2/'. $value;
}
However you should think if you really want to store the path in DB this way. What if you will want to change it in future? You will have to update all the records?

Laravel file upload confusion

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().

Categories