I have a form, I have troubles in Upload an Image :(
I am trying to upload some image and I don't know what I am doing bad :(
{{ Form::open (['route' => 'titulos.store', 'class'=> 'form', 'files'=> 'true']) }}
{{ Form::label('title', "Titulo:", ['class' => 'col-sm-2 control-label']) }}
{{ Form::text('title') }}
{{ $errors->first('title') }}
<div class="form-group">
{{ Form::label('date', "Fecha:", ['class' => 'col-sm-2 control-label']) }}
<input type="date" name="date" >
</div>
{{ Form::label('description', "Description:", ['class' => 'col-sm-2 control-label']) }}
{{ Form::textarea('description') }}
{{ $errors->first('description') }}
<div class="form-group">
{{ Form::file('image') }}
</div>
{{ Form::label('category_id', 'Category:', ['class' => 'col-sm-2 control-label']) }}
<div class="col-sm-10">
{{ Form::select('category_id', array('1' => 'TBLeaks', '2' => 'Quejas', '3' => 'Denuncias', '4' => 'Ideas'), null, array('class' => 'form-control')) }}
</div>
<div class="row">
<div class="col-sm-offset-2 col-sm-10">
{{ Form::submit('Submit', ['class' => "btn btn-primary"]) }}
</div>
</div>
<div class="row">
<div class="col-sm-offset-2 col-sm-10">
<a class="btn btn-success" href="{{ URL::to('admin') }}">Back to Admin</a>
</div>
</div>
{{ Form::close() }}
</div>
#if(Session::has('message'))
<div class="alert alert-{{ Session::get('class') }}">{{ Session::get('message')}}</div>
#endif
#stop
In my store function I have:
class TitulosController extends BaseController {
public function store(){
$rules = array(
'title' => 'required',
'description' => 'required',
'category_id' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// proceso de valicion
if ($validator->fails()) {
return Redirect::to('titulos/create')
->withErrors($validator)
->withInput()->withErrors($validator);
} else {
//store
$image = Input::file('image');
$filename = $image->getClientOriginalName();
if(Input::hasFile('image')){
Input::file('image')->move(public_path().'/assets/img/', $filename);
}
$titulo = new Titulo();
$titulo->id = Input::get('id');
$titulo->title = Input::get('title');
$titulo->description = Input::get('description');
$titulo->date = Input::get('date');
$titulo->image = Input::$filename('image');
$titulo->category_id = Input::get('category_id');
$titulo->save();
return Redirect::to('titulos');
}
I have this model for the Titulo table:
class Titulo extends Eloquent {
use SoftDeletingTrait; // for soft delete
protected $dates = ['deleted_at']; // for soft delete
protected $table = 'titulos';
protected $primaryKey = 'id';
protected $fillable = array('image');
public $timestamps = true;
public function __construct() {
parent::__construct();
}
public function category(){
return $this->belongsTo('Category');
}
}
I have this for Image model:
class Image extends Eloquent {
public $timestamps = false;
protected $fillable = array('image');
}
At this line where your store to public path should be no problem
if(Input::hasFile('image')){
Input::file('image')->move(public_path().'/assets/img/', $filename);
}
Only your save Tutilo object looks not good. I think you have mistakenly add $ on Input::filename at this line. which will call the image
$titulo->image = Input::$filename('image');
change your code to this
$titulo = new Titulo();
$titulo->id = Input::get('id');
$titulo->title = Input::get('title');
$titulo->description = Input::get('description');
$titulo->date = Input::get('date');
$titulo->image = $filename; // I change this line. assuming you want to store the file name
$titulo->category_id = Input::get('category_id');
Related
I am having trouble when I try to upload video/movie to my site. It doesn't save the video in the database, but it makes a folder 'movie' in my files with that video in it like it's supposed to. Also I edited my php.ini file for size requirements and session that I made says that it uploaded. Here is my code
View:
<div class="col-md-6">
{!! Form::open(['method'=>'POST', 'action'=> 'MovieController#store', 'files' => true]) !!}
<div class="form-group">
{!! Form::label('movie_name', 'Enter Movie Name:') !!} <br>
{!! Form::text('movie_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('uploaded_path', 'Select Movie:') !!} <br>
{!! Form::file('uploaded_path', null, ['class'=>'form-control'])!!}
</div>
</div>
<div class="form-group">
{!! Form::label('actor_id', 'Actors:') !!}
{!! Form::select('actor_id[]', $actors, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id[]', $categories, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
MovieRequest:
public function rules()
{
return [
'movie_name' => 'required|max:255',
'uploaded_path' => 'mimetypes:video/avi,video/mpeg,video/mp4|required'
];
}
Controller:
public function store(MovieRequest $request)
{
DB::beginTransaction();
try {
if ($request->hasFile('uploaded_path')) {
$filenameWithExt = $request->file('uploaded_path')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('uploaded_path')->getClientOriginalExtension();
$fileNameToStore = $filename. '_'.time().'.'.$extension;
$path = $request->file('uploaded_path')->storeAs('public/movies/', $fileNameToStore);
} else {
$fileNameToStore = 'novideo.mp4';
}
$movie = new Movie;
$movie->movie_name = $request->input('movie_name');
$movie->uploaded_path = $fileNameToStore;
$movie->actors()->attach($request->input('actor_id'));
$movie->categories()->attach($request->input('category_id'));
$movie->save();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
}
Session::flash('success', 'A movie was successfully UPLOADED in the database!');
return redirect()->route('movies.index');
}
Don’t forget to add:
enctype="multipart/form-data"
to movie field.
I'm trying to update some data with image. The other data is updated but the image still not updated. here's my code
route
Route::get('film/{idFilm}/edit', array('as' => 'film.edit', 'uses' => 'FilmController#edit'));
Route::post('film/{idFilm}/update', array('as' => 'film.update', 'uses' => 'FilmController#update'));
controller
public function edit($idFilm)
{
$film = Film::findOrFail($idFilm);
$genre = Genre::lists('namaGenre', 'idGenre');
if (is_null($film))
{
return Redirect::to('film');
}
return View::make('pengelolaan.film.editfilm', compact('film','genre'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($idFilm)
{
$rules = array(
'judulFilm' => 'required',
'durasi' => 'required|numeric',
'keterangan' => 'required',
'idGenre' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
return Redirect::to('film/' . $idFilm . '/edit')
->withErrors($validation)
->withInput()
->with('message', 'There were validation errors.');
}
else
{
$films = Film::find($idFilm);
$films->judulFilm=Input::get('judulFilm');
$films->durasi=Input::get('durasi');
$films->keterangan= Input::get('keterangan');
$films->idGenre= Input::get('idGenre');
if(Input::hasFile('foto'))
{
$file=Input::file('foto');
$file->move('img',$file->getClientOriginalName());
$filename=$file->getClientOriginalName();
$films->foto = $filename;
$films->save();
}
else
{
$films->save();
}
Session::flash('message', 'Data Berhasil Diubah');
return Redirect::to('film');
}
}
view
{{Form::model($film, array('route'=>array('film.update', $film->idFilm,'files' => TRUE)))}}
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('judulFilm', 'Judul Film') }}
{{ Form::text('judulFilm', Input::old('judulFilm'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('durasi', 'Durasi Film') }}
{{ Form::text('durasi', Input::old('durasi'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('keterangan', 'Sinopsis Film') }}
{{ Form::textarea('keterangan', Input::old('keterangan'), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('idGenre', 'Genre') }}
{{ Form::select('idGenre', $genre,'',array('class'=>'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
{{ Form::label('foto', 'Poster') }}
{{ Form::file('foto') }}
</div>
</div>
</br>
<div class="form-group">
<div class="col-lg-6">
<a class="btn btn-default " href="{{ url('film') }}">Batal</a>
{{Form::submit('Simpan', array('type'=>'submit', 'class'=>'btn btn-default'))}}
{{Form::close()}}
There's no error so i don't know whats wrong with it.
Can someone please tell me what's wrong? Thanks in advance
There are few possibilities to face this issue :
Check for have enctype="multipart/form-data" attribute
Check your file size. If your file size is too high increase upload_max_filesize
May be permission dined for your tmp folder. Provide permission for your tem folder. ini_get('upload_tmp_dir');
I have problem with my creating offers form.
Page displays nicely, but when you add data and after sending form, page gives error.
Laravel 4
enter link description here
My routes:
Route::get('/user/{username}', array(
'as' => 'profile-user',
'uses' => 'ProfileController#user'
));
Route::get('/profile/offers', array(
'as' => 'profile-offers',
'uses' => 'OffersController#offers'
));
Route::post('/profile/offers', array(
'as' => 'profile-offers',
'uses' => 'OffersController#postDestroy' ));
Route::post('/profile/offers/create', array(
'as' => 'profile-create',
'uses' => 'OffersController#postCreate'
));
My controller
controllers/OffersController.php
<?php
class OffersController extends BaseController {
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('user');
}
public function Offers() {
$offers = array();
foreach(Category::all() as $category) {
$categories[$category->id] = $category->name;
}
//return View::make('offers.index')
return View::make('profile.offers')
->with('offers', Offer::all())
->with('categories', $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all(), Offer::$rules);
if($validator->passes()){
$offer = new Offer;
$offer->category_id = Input::get('category_id');
$offer->title = Input::get('title');
$offer->description = Input::get('description');
$offer->price = Input::get('price');
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s').'.'.$image->getClientOriginalName();
$path = public_path('img/offers/' . $filename);
Image::make($image->hetRealPath())->resize(468, 249)->save('public/img/offers/'.$filename);
$offer->image = 'img/offers/'.$filename;
$offer->save();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers.create') //
->with('global', 'Dodano ogloszenie');
}
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')
->with('global', 'Cos poszlo nie tak')
->withErrors($validator)
->withInput();
}
public function postDestroy(){
$offer = Offer::find(Input::get('id'));
if ($offer){
File::delete('public/'.$offer->image);
$offer->delete();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers.destroy')
->with('global', 'Skasowano ogłoszenie');
}
}
public function postToggleAvailability() {
$offer = Offer::find(Input::get('id'));
if ($offer){
$offer->availability = Input::get('availability');
$offer->save();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')->with('global', 'Zaktualizowano')
->with('global', 'Zaktualizowano');
}
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')->with('global', 'zle ogloszenie')
->with('global', 'Zaktualizowano');
}
}
my views
views/profile/offers
<h1>Offerts</h1>
<ul>
#foreach($offers as $offer)
<li>
{{ HTML::image($offer->image, $offer->title, array('width'=>'50')) }}
{{ $offer->title }} -
{{ Form::open(array('url'=>'profile/offers/destroy', 'class'=>'form-inline')) }}
{{ Form::hidden('id', $offer->id) }}
{{ Form::submit('delete') }}
{{ Form::close() }} -
{{ Form::open(array('url'=>'profile/offers/toggle-availability', 'class'=>'form-inline')) }}
{{ Form::hidden('id', $offer->id) }}
{{ Form::select('availability', array('1'=>'In Stock', 'O'=>'Out of Stock'), $offer->availability)}}
{{ Form::submit('Update') }}
{{ Form::close() }}
</li>
#endforeach
</ul>
<h2>Create new offers</h2><hr>
#if($errors->has())
<div id="form-errors">
<p>the following errors have occurred:</p>
<ul>
#foreach($errors->all() as $error)
<li>{{ error }}</li>
#endforeach
</ul>
</div>
#endif
{{ Form::open(array('url'=>'profile/offers', 'method' => 'POST', 'files'=>true)) }}
<p>
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form:: text('title', null, array('class' => 'form-control', 'required' => '')) }}
</p>
<p>
{{ Form::label('description') }}
{{ Form:: text('description', null, array('class' => 'form-control', 'required' => '')) }}
</p>
<p>
{{ Form::label('price') }}
{{ Form::text('price', null, array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('image', 'Choose an image') }}
{{ Form::file('image') }}
</p>
{{ Form::submit('Create offers', array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
My models/Offer.php
<?php
class Offer extends Eloquent {
protected $fillable = array('category_id,', 'title', 'description', 'price', 'availability', 'image');
public static $rules = array(
'category_id'=>'required|integer',
'title'=>'required|min:2',
'description'=>'required|min:20',
'price'=>'required|numeric',
'availability'=>'integer',
'image'=>'required|image|mimes:jpge,jpg,bmp,png,gif'
);
public function category() {
return $this->belongsTo('Category');
}
}
You don't have the route for the POST request and have not correctly set-up the routes for the rest of your controller actions, hence the 404 exception. Form submissions have method of POST unless explicitly specified to GET. You also have to properly set the controller action you want. Laravel will not know profile/offers/destroy should route to postDestroy() unless you tell it to.
Route::post('/profile/offers/destroy', array(
'as' => 'profile-destroy',
'uses' => 'OffersController#postDestroy'
));
You have to do this each for your controller action.
I've implemented an option for uploading pictures of employees. It is optional. However, if I try to upload a file that is not valid, it just seems to skip to the show-method, which first of all does not exist, and secondly is never called.
If I edit the form without a file, everything works fine, and the validation also works. If I upload a valid file, it works aswell.
I just don't get why this is happening
Controller:
`public function update($id){
// get the POST data
$new = Input::all();
// get the user
$u = User::find($id);
$picturevalid = true;
if (Input::get('slett') === 'slett') {
$del = $u->employeePicture;
$del->forceDelete();
}
if(Input::hasFile('picture')) {
if ($u->employeePicture) {
$e = $u->employeePicture;
}
else { $e = new Employeepicture(); }
$image = array(Input::file('picture'));
$picturevalid= $e->validate($image);
}
$new['password'] = $u->password;
// attempt validation
if ($u->validate($new, $u->uid) && $picturevalid && (Input::get('groups') || $new['usertype'] == 2))
{
if (Input::hasFile('picture')) {
$imagein = Input::file('picture');
$kid = Session::get('kid');
$uid = $u->uid;
// We should make an url-friendly version of the file
$newname = $uid.'_'.$u->lastname.'_'.$u->firstname.'.'. // newname:kindergarden+kidnr
$imagein->getClientOriginalExtension(); // punktum + filendelse
$thumb_w = 250; // thumbnail size (area cropped in middle of image)
$thumb_h = 300; // thumbnail size (area cropped in middle of image)
$this->resize_then_crop($imagein,$newname,$thumb_w,$thumb_h,/*rgb*/"255","255","255");
//url to be stored in the database
$urlpath = '/Hovedprosjekt/app/storage/upload/'.$kid.'/images/thumbs/';
$url = $urlpath.$newname;
$e->uid = $uid;
$e->url = $url;
$e->updated_at = date('Y-m-d H:i:s');
if(!$e->save())
{
//save unsuccessful
return Redirect::to('employee/'.$id.'/edit')
->with('register_message', 'Endring feilet.');
}
}
$u->firstname = $new['firstname'];
$u->lastname = $new['lastname'];
$u->phone = $new['phone'];
$u->address = $new['address'];
$u->email = $new['email'];
$u->zipcode = $new['zipcode'];
$u->updated_at = date('Y-m-d H:i:s');
$usertype = Usertype::find($new['utid']);
$u = $usertype->user()->save($u);
//saves user to db
if($u->save())
{
if($new['utid'] == 2){
//Styrer
$kid = Session::get('kid');
$kindergarden = Kindergarden::find($kid);
$u->group()->sync(array($kindergarden->leaderGroup()->gid));
}
else {
$groups = Input::get('groups');
if(is_array($groups))
{
$u->group()->sync($groups);
}
}
return Redirect::to('employee')
->with('message', 'Ansatt endret!');
}
else
{
//save unsuccessful
return Redirect::to('employee/' . $id . '/edit')
->with('register_message', 'Endring feilet.');
}
}
else
{
//validation unsuccessful
//Get validadtion errors
$errors = $u->errors();
if(Input::hasFile('picture')) {
$perrors = $e->errors();
if(isset($perrors)){
foreach($perrors->all() as $perror){
$errors->add($perror);
}
}
}
return Redirect::to('employee/'.$id.'/edit')
->withErrors($errors) // send back all errors to the login form
->withInput(Input::all()); // send back the input (not the password) so that we can repopulate the form
}
}`
Models:
Employeepicture.php
`private $rules = array(
'picture' => 'mimes:jpg,png,gif'
);
private $errors;
/**
* Validation method
*
* #return boolean
*/
public function validate($data) {
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails()) { // set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}`
User.php
`private $rules = array(
'firstname' => 'required|max:40',
'lastname' => 'required|max:40',
'email' => 'required|email|unique:user', // make sure the email is an actual email
'phone' => 'required|numeric|digits_between:7,20',
'address' => 'required|min:3',
'picture' => 'mimes:jpg,jpeg,png,gif|max:2046',
'zipcode' => 'required|numeric|digits_between:1,4'
//'password' => 'required|min:3',
//'password_confirmation' => 'same:password'//required?
);
/**
* Valditation errors
*/
private $errors;
/**
* Validation method
*
* #return boolean
*/
public function validate($data, $update)
{
if (isset($update)) {
$this->rules['email'] = 'required|email|unique:user,email,' . $update . ',uid';
}
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails())
{
// set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}
/**
* Validation errors
*/
public function errors()
{
return $this->errors;
}`
The edit view:
`#extends('employee.employeelayout')
#section('title', 'Endre ansatt')
#section('employeecontent')
<h3>Endre ansatt</h3>
#if (Session::has('register_message'))
<div id="register_message"><p>{{ Session::get('register_message') }}</p></div>
#endif
<ul>
#foreach($errors->all() as $error)
<li>{{ str_replace($eng, $nor, $error) }}</li>
#endforeach
</ul>
{{ Form::model($employee, array('route' => array('employee.update', $employee->uid), 'method' => 'PUT', 'files'=>true)) }}
<div class="form-group">
{{ Form::label('firstname', 'Fornavn', array('class'=>'control-label')) }}
{{ Form::text('firstname', null, array('class'=>'form-control', 'placeholder'=>'Fornavn')) }}
</div>
<div class="form-group">
{{ Form::label('lastname', 'Etternavn', array('class'=>'control-label')) }}
{{ Form::text('lastname', null, array('class'=>'form-control', 'placeholder'=>'Etternavn')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'E-post', array('class'=>'control-label')) }}
{{ Form::text('email', null, array('class'=>'form-control', 'placeholder'=>'E-post')) }}
</div>
<div class="form-group">
{{ Form::label('phone', 'Telefonnummer', array('class'=>'control-label')) }}
{{ Form::text('phone', null, array('class'=>'form-control', 'placeholder'=>'Telefonnummer')) }}
</div>
<div class="form-group">
{{ Form::label('address', 'Adresse', array('class'=>'control-label')) }}
{{ Form::text('address', null, array('class'=>'form-control', 'placeholder'=>'Adresse')) }}
</div>
<div class="form-group">
{{ Form::text('zipcode', null, array('class'=>'form-control', 'placeholder'=>'Postnummer')) }}
</div>
<div class="form-group">
{{ Form::label('image', 'Bilde av ansatt(valgfritt): ') }}
{{ Form::file('picture', null, array('class'=>'input-block-level', 'placeholder'=>'Picture')) }}
#if($employee->employeePicture)
<h5>Nåværende bilde</h5>
<img class="small-pic" src="{{$employee->employeePicture->url}}"/><br>
{{ Form::checkbox('slett', 'slett'); }} Fjern
#endif
</div>
<div class="form-group">
{{ Form::label('utid', 'Brukertype', array('class'=>'control-label')) }}
{{ Form::select('utid', $usertypes, $employee->utid, array('class'=>'form-control','id'=>"select_usertype")) }}
</div>
<div class="form-group" id="group">
{{ Form::label('group', 'Avdeling', array('class'=>'control-label')) }}
#foreach($groups as $group)
#if ($employee->group->contains($group->gid))
<div class='checkbox'>{{ Form::checkbox('groups[]', $group->gid, true) }} {{ $group->name }}</div>
#else
<div class='checkbox'>{{ Form::checkbox('groups[]', $group->gid) }} {{ $group->name }}</div>
#endif
#endforeach
</div>
<div class="pull-right">
{{ Form::submit('Endre', array('class'=>'btn btn-primary'))}}
</div>
{{ Form::close() }}
<a class="btn btn-primary" href="{{ URL::to('employee') }}"><span class="glyphicon glyphicon-arrow-left"></span> Tilbake</a>`
I am in the progress of making a form to edit an existing entry in the database. I am using the Form::model approach to do this, however it doesn't seem to work. The fields just stay empty.
ServerController.php
/**
* Editing servers
*/
public function edit($name)
{
$server = Server::find($name);
$keywords = ($server->getKeywords()) ? $server->getKeywords() : array();
$countries = $this->getCountries();
return View::make('server/edit', array('server' => $server, 'countries' => $countries));
}
public function update($name)
{
$server = Server::find($name);
// Did it succeed?
if($server->save()) {
Session::flash('success', 'You server was edited!');
return Redirect::route('server.view', array($name));
}
// Did not validate
if(Input::get('keywords')) {
$keywords = Input::get('keywords');
Session::flash('keywords', $keywords);
}
Session::flash('danger', "<b>Oops! There were some problems processing your update</b><br/>" . implode("<br/>", $server->errors()->all()));
return Redirect::route('server.edit', array($name))->withInput()->withErrors($server->errors());
}
The Form
{{ Form::model($server, array('route' => array('server.update', $server->name), 'class' => 'form-horizontal', 'role' => 'form', 'files' => true)) }}
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
{{ Form::label('email', 'Email', array('class' => 'control-label col-md-4')) }}
<div class="col-md-4">
{{ Form::text('email', '', array('class' => 'form-control')) }}
{{ $errors->first('email', '<br/><div class="alert alert-danger">:message</div>') }}
</div>
</div>
(some more fields)
{{ Form::close() }}
The problem here is that you're passing in an empty string as the default field value. As the documentation states here, any explicitly passed values will overrule the model attribute data. Try using null instead of '':
{{ Form::text('email', null, array('class' => 'form-control')) }}