Laravel post form error - php

I'm having a problem for the first time when i submit a form.
When i submit the form it doesn't go to post route and i don't know why.
my post route is that:
Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
And my html:
<div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
#if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
#endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
I'm loading this from from a jquery get:
function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
When i try to submit the form i'm getting 302 found in network console from chrome.
I'm doing forms at this way and it is happens for the first time. Anyone can help me?
Thanks

Fix the name attribute for your image upload field. You refer it as image in the form but you are trying to fetch it as file in your controller.

Related

Update image won't work

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');

Getting information from one table and saving the returned information in new table - Laravel 5.2

I'm making a school system for my school and I have this problem in which I'm stuck for days. In my app I have users with type admin, teacher and student. The admin creates all the users and all the other information. Now I'm making the teacher panel in which the teacher will be able to add marks for the students and later they will be displayed in the student panel.
So in first place when the teachers get into their account he will be able to pick a class which he teaches and the subjects which he teaches, for that case I have table - class_subjects in which I'm saving the teacher_id, subject_id and class_id from the admin panel. I'm calling this here, in my teacher panel, and it seems to work just fine, because I see the exact classes and subjects I need. After that I need to make a post query with these both picked from the teacher and in return to get all the students from the picked class + the picked subject, that also works exactly how I want it. So what I am returning is a new blade with arrays with information from the table class_subject, from this returned arrays the teacher need to pick information, and here in text field he must add his mark for the student he picks. After that I need to save the picked information in new table called student_marks with fields student_id, subject_id, mark_type_id, mark.
My question is how the save this information (that the teacher picks) in the new table (student_marks)?
I'm posting the controller:
class AccountController extends Controller
{
public function getIndex() {
$user = Auth::user();
$classStudent = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('class_id');
$userSubject = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('subject_id');
return view('educator.account.account',[
'user' => $user,
'userTeacher'=> $classStudent,
'userSubject'=> $userSubject,
]);
}
public function postIndex(Request $request) {
ClassSubject::where(
'subject_id','=',$request->get('userSubject'),
'class_id','=',$request->get('userClass')
);
$user = Auth::user();
$markType = MarkType::lists('type');
$sub = Subject::where('id','=',$request->get('userSubject'))->get()->lists('name');
$stu = User::where('class_id','=',$request->get('userClass'))
->orderBy('first_name', 'asc')->get()->lists('full_name');
return view('educator.account.input', [
'user' => $user,
'studentss'=> $stu,
'markType' => $markType ,
'sub'=> $sub,
}
I know its a bit twisted but I'm really stuck in here and I will be really grateful if someone can finally help me with this. If something is unclear, please ask.
educator.account.account (first blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-6">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Избери клас:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userClass', $userTeacher, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div class="form-group">
{!! Form::label('profile_id','Избери предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userSubject', $userSubject, null, ['class'=>'form-control']) !!}
</div>
</div>
<div align="center">
{!! Form::submit('Избери', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
#stop
</div>
educator.account.input (second blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-8">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Ученик:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userStu', $studentss, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-2">
{!! Form::text('mark',null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Тип оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('markType', $markType, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('stuSub', $sub, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div align="center">
<button type="button" class="btn btn-default">Назад</button>
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
When they submit the form for the student rating, you'll have a route similar to this to post to:
class AccountController extends Controller {
public function markStudent(Request $request)
{
// get request data
$mark = $request->input('mark');
$subject_id = $request->input('stuSub');
$mark_type = $request->input('markType');
$student_id = $request->input('userStu');
// get the existing record or create a new, empty record
$student_mark = StudentMark::firstOrNew(compact('student_id', 'subject_id'));
// add the updated data to the model
$student_mark->fill(compact('mark_type', 'mark'));
// persist to database
$student_mark->save();
// redirect or do whatever you want after request completion...
}
}
This above code assumes you only want one entry per student, per subject (ie. a unique index on both these columns).
I would also recommend that you validate the data before inserting it, either by doing so before the StudentMark::firstOrNew() or by creating a custom request object with validation.

Laravel: How to bind form data

Scenario:
I have a form for each subject and each subject have three or four questions and the user have to answer those question then save the data on the database
The problem:
How to bind the data with the form so the form refilled with the data that inputted before by the user.
I have tried a lot and search a lot to find a solution but I didn't find anything useful.
Code:
Controller:
public function saveData(Request $request, $user_id, $subject_id)
{
$all_data = $request->input('row');
foreach ($all_data as $data) {
$question_id = $data['question_id'];
$check_data = ['user_id' => $user_id, 'question_id' => $question_id, 'subject_id' => $subject_id];
$exist_data = RatingDatum::where($check_data)->get()->first();
if (is_null($exist_data)) {
RatingDatum::create($data);
} else {
$save = RatingDatum::findorfail($exist_data->id);
$save->update($data);
}
}
flash()->success('Data has been submitted.');
return 'done';
}
View :
<div class="row">
{!! Form::model(['method' => 'PATCH','action'=>['RatingDataController#saveData'],$organisation->id,$organisation->sector->id]) !!}
<div class=" col-md-9">
<h3> {{$subject_name->subject}}</h3>
#foreach($question as $index=>$question)
<div class="plan bg-plan">
<h5>{{$question->question}}</h5>
<hr>
<!-- create sector form -->
#foreach($answers as $answer)
<div class="radio">
<label>
{!! Form::radio('row['.$index.'][answer_id]', $answer->id,true)!!}
{{$answer->answer}}
</label>
</div>
#endforeach
<div class="form-group">
{!! Form::label('comment','Comment :') !!}
{!! Form::textarea('row['.$index.'][comment]' ,null,['class'=>'form-control', 'rows' => 4]) !!}
</div>
</div>
#endforeach
</div>
{!! Form::submit('Submit Data', ['class' => 'btn btn-success submit right']) !!}
{!! Form::close() !!}
</div>

how to Select and Clear all check-boxes using Laravel

I have written a code that sends email to selected people using check-box, now I have to add select all and clear all button so that all the check-boxes should get selected/dis-selected.
Here is my code:
My controller:
public function display(){
$data = Input::get('agree');
$count = count ($data);
$this->contact( $data );
return view('clientinfo.display', compact('data','count'));
}
My View:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET'))!!}
#foreach($clients as $client)
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email]) !!}
<article>
{{ $client->user_name }}
{{ $client->email }}
</article>
#endforeach
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
<br/>
#include('clientinfo.newmember')
#stop
if i add a button in my view naming select-all and clear-all how do i relate them, to select all the members within list?
You could give the checkboxes a class and use jquery.
You also need a checkbox that says "select all" with an ID.
$(function() {
$('#selectAll').click(function() {
if ($(this).prop('checked')) {
$('.your_checkbox_class').prop('checked', true);
} else {
$('.your_checkbox_class').prop('checked', false);
}
});
});
PS: Code is not tested
I have made changes to my code and it worked using JavaScript.
Here is my code:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET','name'=>'f1' , 'id'=>'form_id'))!!}
<br/>
#foreach($clients as $client)
<div class="form-group">
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email], ['class' => 'questionCheckBox']), $client->email !!}
<br/>
</div>
#endforeach
<div class="form-group">
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
</div>
<div class="form-group">
{!! Form::button('Select All',['class' => 'btn btn-info form-control','onClick'=>'select_all("agree", "1")']) !!}
</div>
<div class="form-group">
{!! Form::button('Clear All',['class' => 'btn btn-danger form-control','onClick'=>'select_all("agree", "0")']) !!}
</div>
{!! Form::close() !!}
#stop
#endsection
And in my master file,I have added a JavaScript:
<script type="text/javascript">
var formblock;
var forminputs;
function prepare() {
formblock= document.getElementById('form_id');
forminputs = formblock.getElementsByTagName('input');
}
function select_all(name, value) {
for (i = 0; i < forminputs.length; i++) {
// regex here to check name attribute
var regex = new RegExp(name, "i");
if (regex.test(forminputs[i].getAttribute('name'))) {
if (value == '1') {
forminputs[i].checked = true;
} else {
forminputs[i].checked = false;
}
}
}
}
if (window.addEventListener) {
window.addEventListener("load", prepare, false);
} else if (window.attachEvent) {
window.attachEvent("onload", prepare)
} else if (document.getElementById) {
window.onload = prepare;
}
</script>
Earlier i was doing this using Jquery, that was not working, then i tried using JavaScript and it worked.
I have tried various ways to add jquery in my code which are given in answers of stackoverflow.com, but nothing worked in laravel. If anyone know how to use jquery in laravel, please leave a comment.

Dropzone shows upload success but file is not uploaded in Laravel 5

I'm still learning Laravel and trying to build some sort of an article management system. As part of form for inserting new articles I want to also upload multiple pictures of them. The upload shows success, yet there is no file in uploads folder. Here is my form code:
{!! Form::open(['route' => 'admin_artikli.store', 'class' => 'dropzone', 'id' => 'create_artikal', 'enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{!! Form::label('Firma', 'Firma') !!}
{!! Form::text('firma_id', Input::old('firma_id'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Naziv', 'Naziv') !!}
{!! Form::text('naziv', Input::old('naziv'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Opis', 'Opis') !!}
{!! Form::text('opis', Input::old('opis'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Cijena', 'Cijena') !!}
{!! Form::text('cijena', Input::old('cijena'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('kolicina', 'kolicina') !!}
{!! Form::text('kolicina', Input::old('kolicina'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('dostupnost', 'dostupnost') !!}
{!! Form::text('dostupnost', Input::old('dostupnost'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::select('aktivan', array('D' => 'Aktivan', 'N' => 'Neaktivan'), 'D') !!}
</div>
<div class="form-group">
{!! Form::select('aktivan', array('D' => 'Aktivan', 'N' => 'Neaktivan'), 'D') !!}
</div>
{!! Form::submit('Kreiraj artikal', array('class' => 'btn btn-primary', 'id' => 'create_artikal_submit')) !!}
{!! Form::close() !!}
My routes.php(showing only relevant):
Route::post('/upload', 'ArtikalAdminController#upload');
Route::resource('admin_artikli', 'ArtikalAdminController');
My controller methods for store and upload:
public function upload(){
$input = Input::all();
$rules = array(
'file' => 'image|max:3000'
);
echo "eldaaaaaaaaaaaaaaaaaaaaaaaaar";
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Response::make($validation->errors->first(), 400);
}
$file = Input::file('file');
$extension = File::extension($file['name']);
$directory = public_path().'uploads/'.sha1(time());
$filename = sha1(time().time()).".{$extension}";
$file->move($directory, $filename);
$upload_success = Input::file('file', $directory, $filename)->move($directory, $filename);;
echo $directory;
if( $upload_success ) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
}
public function store(Request $request)
{
$artikal = new Artikal;
$artikal->firma_id = Input::get('firma_id');
$artikal->naziv = Input::get('naziv');
$artikal->sifra = Input::get('sifra');
$artikal->opis = Input::get('opis');
$artikal->cijena = Input::get('cijena');
$artikal->kolicina = Input::get('kolicina');
$artikal->dostupnost = Input::get('dostupnost');
$artikal->aktivan = Input::get('aktivan');
$artikal->save();
Session::flash('flash_message', 'Uspješno unesen artikal!');
//return redirect()->back();
}
Finally, dropzone options I am currently using:
Dropzone.options.createArtikal = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
maxFiles: 10,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
var element = document.getElementById('create_artikal_submit');
var form = document.getElementById('create_artikal');
element.addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
form.submit();
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
I know this is lacking many things, but I'm trying to go on step at a time and I'm stuck here. When I check the network tab of dev tools I see XHR requests are 200 OK, but yet I see no file.
You forgot to write 'files' => true in form, update form & try.
{!! Form::open(['route' => 'admin_artikli.store', 'class' => 'dropzone', 'id' => 'create_artikal', 'files'=>true, 'enctype' => 'multipart/form-data' ]) !!}

Categories