I would like to design a form in Laravel which takes an image the User has selected, uploads it to the server and stores the image path in a 'image' field and also accepts a 'text' field which describes the image. I do not know how to store both the text field and image as an array to pass to the controller.
The Form
<div class="form-group">
{{ Form::label('description', trans('main.poster')) }}
{{ Form::text('description', Input::old('poster'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::file('image','files' => true) }}
</div>
<button type="submit" class="btn btn-success">{{ trans('dash.update') }}</button>
Controller
public function store()
{
$input = array('image' => Input::file('image'));
if ( ! $this->validator->setRules('image')->with($input)->passes())
{
return Redirect::back()->withErrors($this->validator->errors());
}
$this->title->uploadImage($input);
return Redirect::back()->withSuccess( trans('main.uploaded image success') );
Upload image
public function uploadImage(array $input)
{
$name = str_random(25);
$insert = array('image' => asset('assets/images/'.$name.'.jpg'), );
$this->images->saveTitleImage($input, $name);
}
Save image path
public function saveTitleImage($input, $name)
{
$encoded = Imagine::make($input['image']->getRealPath())
->encode('jpg');
Imagine::make($encoded)->save(public_path('assets/images/'.$name.'.jpg'));
}
Related
My problem is that i upload a image on the website in laravel but the database save the path of my local storage with a strange name and extension:
The picture was uploaded fine in Storage/app/public but with another name (Like a hash code):
Now, how can get this name in /Storage/Public with a query on a database, or how can upload the image with the original name or by ID?
Code:
Form upload:
<form class="formulario" method="POST" enctype='multipart/form-data' action="{{ route('add_taller') }}">
#csrf
<h4>Añade el titulo correspondiente</h4><input name="titulo">
<h4>Añade un logo al taller</h4><input type="file" name="icono" class="taller_form {{ $errors->has('name') ? 'alert alert-danger' : ''}}" />
{!! $errors->first('image', '<p class="alerta">:message</p>') !!}
<h4>Añade una descripción</h4><textarea name="descripcion" rows="10" cols="50" value="{{ old('textarea') }}"></textarea>
{!! $errors->first('string', '<p class="alerta">:message</p>') !!}
<button type="submit">Subir a la web</button>
</form>
In controller:
public function add_taller(Request $request)
{
$request->file('icono')->store('public');
$user = Auth::user();
DB::table('talleres')->insert([
'icono' =>$request->icono,
'titulo' => $request->titulo,
'descripcion' => $request->descripcion,
'user_id' => $user->id,
'fecha'=> now()]);
return view('home');
}
View where I need to show the picture:
#foreach($datos as $dato)
<div class="taller">
<div>
<img src="{{Storage::url($dato->icono)}}" alt="" srcset="" class="icon_taller">
</div>
<div>
<h4>{{$dato->titulo}}</h4>
<p>{{$dato->descripcion}}</p>
</div>
<div class="botones_area">
<button>Descarga</button>
<button>Contacto</button>
</div>
</div>
#endforeach
As I can see, you don't save the path with the file extension.
When you use $request->file('icono')->store('public'); you generate a temporal file and the file extension is determined by Laravel with the MIME type.
What's about:
public function add_taller(Request $request)
{
$path = Storage::putFileAs(
'public', $request->file('icono'), Str::uuid()
);
$user = Auth::user();
DB::table('talleres')->insert([
'icono' => $path,
'titulo' => $request->titulo,
'descripcion' => $request->description,
'user_id' => $user->id,
'fecha'=> now()]
);
return view('home');
}
For the filename, I've used Str::uuid function to generate names with a different id. For store files, I've used Storage Laravel facade, take a quick look here: https://laravel.com/docs/8.x/filesystem#specifying-a-file-name
What do you think about these changes?
Controller article
public function update(Request $request, Article $article){
$article->update($request->except('slug', 'image_path'));
if ($request->hasFile('image_path')) {
$image = $request->file('image_path');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$article->image_path = $new_name;
$article->save();
}
$article->categories()->detach();
if ($request->has('categories')) {
$article->categories()->attach($request->input('categories'));
}
$user=auth()->user();
return redirect()->back()->with('message', 'Raksts atjaunots!');
}
public function edit(Article $article){
$user=auth()->user();
return view('edit',[
'article' => $article,
'categories' => Category::with('children')->where('parent_id',0)->get(),
'delimiter' => ''
]);
}
edit blade
<form class="form-horizontal" action="{{route('update', $article)}}" method="post" enctype="multipart/form-data" style="display: flex;justify-content: center;flex-direction: column;">
<input type="hidden" name="_method" value="put">
{{ csrf_field() }}
{{-- Form include --}}
<img src="{{URL::to('/images').'/'.$article->image_path}}" alt="">
#include('partials.form')
<input type="hidden" name="modified_by" value="{{Auth::id()}}">
</form>
link to the form
<tbody>
#foreach ($articles_suggest_user as $article)
<a class="btn btn-default" href="{{route('edit', $article)}}"><i class="fa fa-edit"></i></a>
<?php } ?>
#endforeach
</tbody>
web.php
Route::get('/home/edit/{id}','Controller_Article_parents#edit', function () {
return view('/home/edit');
})->name('edit');
Route::get('/home/update/','Controller_Article_parents#update', function () {
return view('/home');
})->name('update');
When i clicked the link, i move to for example this url http://127.0.0.1:8000/home/edit/190
But my form is empty... input empty. How I can do when I open form it's display me input information ?
When click my link its display me form, but form is empty.
form example
<div class="rtq">
<label for="parent_id">Cat</label>
<span class="required">*</span>
<select
id="parent_id"
class="form-control"
name="categories[]"
multiple=""
required
>
#include('admin.categories.partials.categories',
['categories' => $categories,
'current' => $article,
'delimiter' => $delimiter])
</select>
</div>
<div class="rtq">
<label for="">Descript</label>
<textarea
name="description_short"
class="form-control"
id="description_short"
>
{{ $article->description_short ?? "" }}
</textarea>
</div>
It my form . Mini example
If you want to redirect with form input, you can use the withInput() function
return back()->withInput();
https://laravel.com/docs/7.x/redirects#creating-redirects
Now, this function is designed to be used with form validation and may not be what you want.
What I have done in the past when combining create & edit views into a single template is something like this:
{!! Form::text('name', isset($model) ? $model->name : null, [
'class' => 'form-control',
'placeholder' => 'Please fill out this field &hellips;',
'required' => true
]) !!}
This uses the Laravel Collective HTML library. However the principle is the same if you are using raw hmtl like so:
<input type="text" value="{{ isset($model) ? $model->name : null }}">
Round 2 Electric Boogaloo
You aren't returning a variable called $article to your edit.blade.php.
Round 3 Apple Tree
Originally, you appeared to be calling both a controller action AND also a callback function. Stick to the controller action only like so:
Route::get('/home/edit/{id}','Controller_Article_parents#edit')->name('edit');
Then within your edit() function on the Controller you will want to do this:
public function edit ($id) {
return view('/home/edit', [
'article' => Article::find($id)
]);
}
I want to upload a files to my laravel project. But I recognise that laravel randomly change my file name. How do I upload files to laravel without changing it's name. Also somehow my validation are not working. I just got redirected without any messages.
this are my blade
//show errors
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
/ul>
</div>
#endif
// forms
<form action="{{ route('designers.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group d-flex flex-column">
<label for="exampleInputFile">File input</label>
<input type="file" name="files[]" multiple>
</div>
<button type="submit">Submit</button>
</form>
this are my controller
$data = $request->validate([
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'file',
]);
if ($request->hasFile('files')) {
$allowedfileExtension=['pdf','jpg','png','docx','png','xlsx'];
$files = $request->file('files');
foreach ($files as $key => $value) {
$filename = $value->getClientOriginalName();
$extention = $value->getClientOriginalExtension();
$check = in_array($extention,$allowedfileExtension);
if ($check) {
File::create([
'name' => $value->store('designers','public'),
'type' => 'designer',
'project_id' => $data['project'],
'user_id' => Auth::user()->id,
]);
}
}
}
You can change your controller to this:
use Illuminate\Support\Facades\Storage;
function yourFunction(){
$this->validate($request,[
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'nullable|array|file|mimes:pdf,jpg,png,docx,xlsx' //This validates file and MIME type. Also if it is not required, it should perhaps be nullable.
]);
if($request->hasFile('files'){
$files = $request->file('files');
foreach($files as $file){
$filename = $file->getClientOriginalName();
Storage::disk('local')->put($filename, file_get_contents($file)); //This stores your file.
}
}
//Save stuff to DB here
}
Official doc on file storage: https://laravel.com/docs/5.8/filesystem
Official doc on Validation of MIME: https://laravel.com/docs/5.8/validation#rule-mimes
I am using Laravel 5.2 and I have two forms in different pages but same method and controller..
Both use public function store(Request $request){} method.
First Form in 'show.blade.php' page:
<form action="{{ url('projects') }}" name="comment_form" class="row" method="POST">
{{ csrf_field() }}
<div class="col-md-3">
<input placeholder="Name" name="name" type="text">
</div>
<div class="col-md-3">
<input placeholder="Email" name="email" type="text">
</div>
<div class="col-md-3">
<input placeholder="Subject" name="subject" type="text">
</div>
<div class="col-md-3">
<input value="Id Number : {{ $project -> id }}" name="project_id" type="text" readonly>
</div>
<div class="col-md-12">
<textarea placeholder="Comments" name="comments" cols="10" rows="10"></textarea>
</div>
<div class="col-md-12">
<input type="submit" value="Send Comments">
</div>
</form>
Second Form in 'create.blade.php' page:
{!! Form::open(array('route' => 'projects.store', 'files' => true, 'name' => 'project_form')) !!}
{{ Form::label('title', 'Title:', ['class' => 'top-bottom-margin']) }}
{{ Form::text('title', null, ['class' => 'form-control', 'maxlength' => '255']) }}
{{ Form::label('image', 'Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('image', ['accept' => 'image/*']) }}
{{ Form::label('second_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('second_image', ['accept' => 'image/*']) }}
{{ Form::label('third_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('third_image', ['accept' => 'image/*']) }}
{{ Form::label('body', 'Body:', ['class' => 'top-bottom-margin']) }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
{{ Form::submit('Create Project', ['class' => 'btn btn-success btn-lg btn-block top-bottom-margin']) }}
{!! Form::close() !!}
ProjectsController.php method code:
public function store(Request $request)
{
$data = $request->all();
if(isset($data['project_form'])){
// validation START
$this -> validate($request, array(
'title' => 'required | max:255',
'body' => 'required',
'image' => 'required'
));
// validation END
// storing in database
$project = new Project;
$project -> title = $request -> title;
$project -> body = $request -> body;
// First images START
$image = $request -> file('image');
$fileName = time() . '.' . $image -> getClientOriginalExtension();
$location = public_path('admin_images/' . $fileName);
Image::make($image) -> resize(860, 600) -> save($location);
//database store
$project -> image = $fileName;
//First images END
if ($request->hasFile('second_image')){
// second images START
$rand_number = rand(100, 2000);
$second_image = $request -> file('second_image');
$secondFileName = time() . $rand_number . '.' . $second_image -> getClientOriginalExtension();
$secondLocation = public_path('admin_images/' . $secondFileName);
Image::make($second_image) -> resize(860, 600) -> save($secondLocation);
//database store
$project -> second_image = $secondFileName;
// second images END
}
if ($request->hasFile('third_image')){
// third images START
$second_rand_number = rand(3000, 5000);
$third_image = $request -> file('third_image');
$thirdFileName = time() . $second_rand_number . '.' . $third_image -> getClientOriginalExtension();
$thirdLocation = public_path('admin_images/' . $thirdFileName);
Image::make($third_image) -> resize(860, 600) -> save($thirdLocation);
//database store
$project -> third_image = $thirdFileName;
// third images END
}
$project -> save();
Session::flash('success', 'Your project was created successfully!');
return redirect() -> route('projects.show', $project -> id);
}
Now I check if the comment_form is submitted or the project_form is submitted?
You can create hidden element to pass variable:
{!! Form::hidden('from', 'someView') !!}
And then get it in controller:
if ($request->from == 'someView') {
....
Also, you could pass variable by using sessions and by retrieving previous page URL, but I think hidden form element is the best choice when you're using form.
You could put a name and value to the submit button and check that.
if ($request->get('submit') == 'project') {
// do something
} elseif ($request->get('submit') == 'comment') {
// do something else
}
or use a switch
switch ($request->get('submit')) {
case 'project':
// do something
break;
case 'comment':
// do something else
break;
default:
// do this if above does not apply
break;
}
I'm using Laravel 5.2 and I want to make a form which can upload a pdf file with it. I want to add that file on folder "files" in "public" folder. here is my view:
<div class="form-group">
<label for="upload_file" class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input class="form-control" type="file" name="upload_file" id="upload_file">
</div>
</div>
and what should I do next? what should I add in my controller and route?
First you should add enctype="multipart/form-data" to your <form> tag. Then in your controller handle the file upload as follow:
class FileController extends Controller
{
// ...
public function upload(Request $request)
{
$uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension());
$request->get('upload_file')->move(public_path('files') . $uniqueFileName);
return redirect()->back()->with('success', 'File uploaded successfully.');
}
// ...
}
Link to Laravel Docs for Handling File Uploads
Laravel casts the file type params in request to UploadedFile objects. You can see Symfony's UploadedFile class here for available methods and attributes.
First of all, the documentation tells you exactly what to do here.
What you want to do is adding this to your <form> tag:
enctype="multipart/form-data" (This allows you to upload data), set a method(get/post) and an action (url).
Then you want to set up your routes.
For example:
Route::post('/pdf/upload', 'FileController#upload');
This way you make sure that when you send the form it will go to your FileController with upload as function.
In your controller you want to declare the file as explained in the docs.
$file = $request->file('photo');.
From this point you can do whatever you'd like to do with the file ($file). For example uploading it to your own server.
public function store(Request $request)
{
if($request->file('file'))
{
$file = $request->file('file');
$filename = time() . '.' . $request->file('file')->extension();
$filePath = public_path() . '/files/uploads/';
$file->move($filePath, $filename);
}
}
You Could Use Simple Method It Can Save The File
$path = $request->file('avatar')->store('avatars');
For More Information Here
you can this code for upload file in Laravel:
$request->file('upload_file')->move($path,$name);
You can take a look at how i upload files, all files are accepted:
first the code for the create.blade.php form
{!! Form::open(
array(
'url' => 'uploads',
'method' => 'post',
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true)) !!}
#include('uploadspanel.create_form')
{!! Form::close() !!}
Remember to set files to true
Then the uploadspanel.create_form
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('file', 'Bestand:') !!}
{!! Form::file('file',null,['class'=>'form-control']) !!}
</div>
#if(\Auth::user()->level == 2)
<div class="form-group">
{{ Form::label('approved', 'Beschikbaar voor:') }}
{{ Form::select('approved', array(1 => 'Iedereen', 2 => 'monteurs', 3 => 'concept'), null, ['class' => 'form-control']) }}
</div>
#else
{{ Form::hidden('approved', 3) }}
#endif
<div class="form-group">
{!! Form::submit('Bestanden uploaden',['class' => 'btn btn-primary form-control']) !!}
</div>
then the controller store function
public function store(UploadRequest $request){
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
Input::file('file')->move(
base_path().'/public/files/uploads/', $filename
);
if(\Auth::user()->level == 2) {
$approved = $request['approved'];
} else {
$approved = 3;
}
$fullPath = '/public/files/uploads/' . $filename;
$upload = new Uploads(array(
'name' => $request['name'],
'format' => $extension,
'path' => $fullPath,
'approved' => $approved,
));
$upload->save();
$uploads = Uploads::orderBy('approved')->get();
return view('uploadspanel.index', compact('uploads'));
}