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().
Related
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();
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();
}
How to solve the error?
this is my htm code (button upload)
{{ form_open({files: true, request: 'onFileUpload'}) }}
<!--File Input-->
<input type="file" name="file-upload" required="required">
<!--File Input-->
<!--Submit/Upload Button-->
<button type="submit">Upload</button>
{{ form_close() }}
this is the component php code
public function onFileUpload()
{
$file = new System\Models\File;
$file->data = Input::file('file-upload');
$file->save();
// Attach the uploaded file to your model
$model->file()->add($file);
// The above line assumes you have proper attachOne or attachMany relationships defined on your model
$model->file_path = url('/') . $model->file->getPath();
$model->save();
return Redirect::back();
}
is this the proper attachMany relationship?
public $attachMany = [
'files' => 'System\Models\File',
];
}
I'm not very sure about the code cause I'm new to October cms
Can anyone show some examples?
How to create a drag and drop file uploader component?
You need to new up an instance of the model that you've defined you relationship in and set it as your $model variable.
For example.. your model class could look like this.
class User extends Model
{
public attachMany [
'files' => 'System\Models\File'
];
}
And then in your component onFileUpload()
$model = new User;
$model->files()->add($file);
$model->file_path = url('/') . $model->file->getPath();
$model->save();
Also, just take notice that your attachMany relationship in your model class is defined as files but you're trying to use it with
$model->file()->add();
It should be
$model->files()->add();
I have built a simple application laravel 4. I have scaffolding setup for adding posts which seems to be working fine. I have setup Stapler and image uploading package. When I setup to use single image uploads its pretty good and it works a charm. I recently looked at the docs here
It states that you can do multiple uploads so I went about doing it as explained in the docs. Here are my coded pages:
Post.php model:
<?php
class Post extends Eloquent {
use Codesleeve\Stapler\Stapler;
protected $guarded = array();
// A user has many profile pictures.
public function galleryImages(){
return $this->hasMany('GalleryImage');
}
public static $rules = array(
'title' => 'required',
'body' => 'required'
);
public function __construct(array $attributes = array()) {
$this->hasAttachedFile('picture', [
'styles' => [
'thumbnail' => '100x100',
'large' => '300x300'
],
// 'url' => '/system/:attachment/:id_partition/:style/:filename',
'default_url' => '/:attachment/:style/missing.jpg'
]);
parent::__construct($attributes);
}
}
PostsController.php
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Post::$rules);
if ($validation->passes())
{
$this->post->create($input);
return Redirect::route('posts.index');
}
$post = Post::create(['picture' => Input::file('picture')]);
foreach(Input::file('photos') as $photo)
{
$galleryImage = new GalleryImage();
$galleryImage->photo = $photo;
$user->galleryImages()->save($galleryImage);
}
return Redirect::route('posts.create')
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
This has save functions and other functions inside it too.
GalleryImage.php gallery image model to use in the post controller
<?php
class GalleryImage extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function __construct(array $attributes = array()) {
$this->hasAttachedFile('photo', [
'styles' => [
'thumbnail' => '300x300#'
]
]);
parent::__construct($attributes);
}
// A gallery image belongs to a post.
public function post(){
return $this->belongsTo('Post');
}
}
My create.blade.php template to post the post itself
#extends('layouts.scaffold')
#section('main')
<h1>Create Post</h1>
{{ Form::open(array('route' => 'posts.store', 'files' => true)) }}
<ul>
<li>
{{ Form::label('title', 'Title:') }}
{{ Form::text('title') }}
</li>
<li>
{{ Form::label('body', 'Body:') }}
{{ Form::textarea('body') }}
</li>
<li>
{{ Form::file('picture') }}
</li>
<li>
{{ Form::file( 'photo[]', ['multiple' => true] ) }}
</li>
<li>
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
</ul>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
#stop
When I post the form with a single images attached its fine and saves to the db and it works a treat but when I save it with multiple image uploads I get this error:
ErrorException
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
The full stack trace is here in my gist of the files
Can anyone point out to me why this error happens. From my research its creating a multidimensional array that needs flattening I think but I am unsure if this is true.
I have been banging my head against a brick wall with this for ages.
Problem is when your submitting multiple images it becomes an array of pictures instead of a single string. So its trying to save an array to the database instead of a string which its expecting. If you make it so your photo variable is a json_encoded array of pictures then you should be able to save them.
Hope this helps.
I cant figure out what I am missing. I am trying to have a form submit to a controller method through a named route with all of its input and image->id as a parameter. I keep getting a notfoundhttpexception. If I remove /{$id} from the route declaration I get a missing parameter for controller action error. Here is the code:
The route
Route::post('images/toalbum/{$id}', array('as' => 'imgToAlbum', 'uses' => 'ImagesController#addImageToAlbums'));
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', array('as' => 'home', function()
{
return View::make('layouts.default');
}));
Route::get('users/login', 'UsersController#getLogin');
Route::get('users/logout', 'UsersController#getLogout');
Route::post('users/login', 'UsersController#postLogin');
Route::resource('users', 'UsersController');
Route::resource('images', 'ImagesController');
//routes related to images
Route::post('images/toalbum/{$id}', array('as' => 'imgToAlbum', 'uses' => 'ImagesController#addImageToAlbums'));
Route::resource('videos', 'VideosController');
Route::resource('albums', 'AlbumsController');
view that's submitting the form:
#extends('layouts.default')
#section('content')
<?php
$albumarray = array(null => '');
?>
{{ HTML::image($image['s3Url'], $image['altText']) }}
<p>
Title:{{ $image['caption'] }}</br>
Alt-Text: {{ $image['altText'] }}</br>
Description: {{ $image['description'] }}</br>
</p>
{{ Form::open(array('route' => array('imgToAlbum', $image['id']), 'method' => 'post')); }}
#foreach ($albums as $album)
<?php
array_push ($albumarray, array($album['id'] => $album['caption']));
?>
#endforeach
{{ Form::label('Add image to album?') }}
{{ Form::select('album', $albumarray) }}</br>
{{ Form::submit('Add to Album')}}
{{Form::close();}}
<?php
echo $albums;
?>
#stop
#section('footer')
#stop
controller:
<?php
class ImagesController extends BaseController
{
protected $image;
public function __construct(Image $image)
{
$this->image = $image;
}
// add image to album
public function addImageToAlbums($id)
{
dd($album = Input::all());
$image = $this->where('id', '=', $id);
$image->albumId = $album;
$this->image->save();
/*return Redirect::route('image.show', $this->image->id)
->with('message', 'Your image was added to the album');*/
}
}
Maybe this will help someone in the future so instead of deleting here is the answer. removing the $ from images/toalbum/{$id} in the route declaration has resolved the problem.