Laravel redirect back not passing variable - php

I am creating a simple page to hash strings with md5, however the output is never returned.
This is the controller I use for these pages.
The function md5 is routed to the get and the function md5post is routed to the post.
The view has a form that is posted to the md5post function. it has one variable $input with the string to hash.
<?php
class ConversionsController extends \BaseController {
private $withmd5;
public function __construct(){
$this->withmd5 = [
'pagetitle' => 'MD5 hashing',
'description' => 'description',
'infoWindow' => 'info',
'btnSumbit' => Form::submit('Hash', ['class' => 'btn btn-default'])
];
}
public function md5(){
return View::make("layout.textareamaster")->with($this->withmd5);
}
public function md5post(){
if (strlen(Input::get("input")) > 0)
{
$hash = md5(Input::get("input"));
}
return Redirect::back()->withInput()->with("output", $hash);
}
}
And this is the view
{{ Form::open(['method' => 'post']) }}
<div class="row">
<div class="col-md-6">
<p class="well">
{{ Form::textarea('input', '', ['class' => 'form-control', 'rows' => 5]) }}
<span style="float:right;">
{{ $btnSubmit or Form::submit('Go', ['class' => 'btn btn-default']) }}
</span>
</p>
</div>
<div class="col-md-6">
<p class="well">
<textarea class="form-control" rows="5" readonly="true">{{ $output or "nothing" }}</textarea>
</p>
</div>
</div>
{{ Form::close() }}
When in my template file, the input is always displayed, however, the variable $output is always undefined. I have beent trying to use other variable names, but it wont work.
If I return the variable right before the redirect, I see the correct output.

I have found a solution.
In my view I had to use Session::get() to get the value.
That still didn't return the correct output, but I got it by casting this variable to string.
My solution:
{{ (string)Session::get('output') }}

Related

Getting the number of an object in array, but not the object itself. - Laravel 5.2

I have this problem here with my query.
In my getIndex method I'm listing an array of objects from a table and then in my postIndex when I'm trying to post them it turns out that I'm posting the number of the object in the array, but not the object itself. Why is this happening, someone?
public function getIndex() {
$user = Auth::user();
return view('educator.account.account',[
'user' => $user,
'class'=> ClassSubject::where('teacher_id','=',$user->id)()->lists('class_id'),
'subject'=> ClassSubject::where('teacher_id','=',$user->id)->lists('subject_id'),
]);
}
public function postIndex(Request $request) {
ClassSubject::where([
['subject_id','=',$request->input('subject')],
['class_id','=',$request->input('class')]
])->get();
The form:
<div class="panel panel-default">
<div class=" panel-heading" id="admin-heading"> Добре дошли!</div>
<div class="panel-body">
<br>
{!! Form::open(['action' => 'Educator\AccountController#postIndex', 'class' => 'form form-vertical' ]) !!}
<div class="form-group col-md-6">
<div class="col-md-4">{!! Form::label('class','Избери клас:') !!}</div>
<div class="col-md-6">{!! Form::select('class', $class, null, ['class'=>'form-control']) !!}</div>
</div>
<div class="form-group col-md-6">
<div class="col-md-5">{!! Form::label('subject','Избери предмет:') !!}</div>
<div class="col-md-6">{!! Form::select('subject', $subject, null, ['class'=>'form-control']) !!}</div>
</div>
<div align="center">
<br>
<br>
{!! Form::submit('Избери', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
This might work for you in getIndex():
return view('educator.account.account', [
'user' => $user,
'class'=> ClassSubject::lists('class_id', 'YOUR_HUMAN_READABLE_FIELD')->where('teacher_id', $user->id)->get(),
'subject'=> ClassSubject::lists('subject_id', 'YOUR_HUMAN_READABLE_FIELD')->where('teacher_id', $user->id)->get()',
]);
Let me know if it worked or not.
EDIT
The problem has been fixed, this did the trick:
DB::table('class_subject')->where('teacher_id', $user->id)->pluck('id', 'name');
As you are passing only one parameter you will receive an array with its values set to the column you are passing to lists method.
But Form::select uses array's keys for values of options and values for the display names of options.
So use the lists method as following.
ClassSubject::lists('displayName', 'value')
In laravel 5.2 lists method is deprecated and consider using the pluck method instead which has the same signature.

Laravel form error message

I created a form for myself and it was working perfect. I did some rules like: if the user haven't wrote anything in the form or haven't wrote enough, give me some error message. This was working while used the 'former' package instead of the normally used 'form' package. Now I changed my form from "Former" to "Form" and now my error message are gone.. Well my form works and the rules too. If I don't write anything in my form or not at least 3 characters in the title/content section, it should redirect me with the errors I need. This works, but without the error message.
Here is my form:
#extends('master')
#section('content')
{!! Form::open(array('action' => 'Test\\TestController#store')) !!}
<div class="form-group">
{!! Form::label('thread', 'Title:') !!}
{!! Form::text('thread', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('content', 'Body:') !!}
{!! Form::textarea('content', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Add Thread', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
My Controller#store function:
public function store(StoreRequest $request){
Thread::create($request->all());
return redirect(action('Test\\TestController#index'));
}
my Model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
and now the rules ( StoreRequest.php ) :
<?php
namespace App\Http\Requests\Store;
use App\Http\Requests\Request;
class StoreRequest extends Request {
public function rules() {
return [
'thread' => 'required|min:3',
'content' => 'required|min:3'
];
}
public function authorize() {
return true;
}
}
The error message was getting automaticly generated. Laravel did that for me. But not anymore.
Does anybody see why?
You can check if the form returned any error with something along these line:
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
Or you could use BootForm and let it handle everything for you

Laravel 5.2 validation erros are empty at random moments

I have something very weird going on with my Laravel application's validation. I have an application where a user can only access it with his/hers unique hash/code in the url. When the url with hash matches a user I prefill the form with the user's profile information. The user then has to confirm/complete/modify it the information in using the form. This works fine, but when submitting the form sometimes the validation not behaving normally.
For example, I leave some fields empty that are required and I submit the form, I get redirected back, my errors are shown in the form fields with a nice red border. All good so far. However, for some unknown reason sometimes when submitting the form with an empty value in a field which is required by the validation, it redirects back and shows the profile form pre-filled again, but the errors variable is empty, but the validation still failed!
Their is no line to draw in when this happens, sometimes it happens on the first submit sometimes I have to submit the form 30 times before it happens. For now we tackled it with an extra layer of frontend validation because the app had to go live, but I can't stop thinking about why and how this is happening.
I'm using a Request class for validation, but I also tried creating a manual validator in my controller, but that has exactly the same behaviour. I first thought that it has something to do with pre-filling the form, so I tried that when there are errors and I don't prefill anything (except input old of course), but the problem still exists.
The weirdest part of it all is that the errors are empty, but some required fields were not filled (and their names are correct) because the problem does not always happens. I have been unable to reproduce the problem on my local and staging env, but it keeps happening on my live server.
It would be great if someone had any suggestions on what I'm doing wrong or what I happening. I did this 1000 of times the only difference with other times is that I prefill the form, but I also have it when I turn that feature off.
Edit: as requested my code below.
Note: I replaced some keywords like routes, redirects and relation names.
Request class
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class RegistrationRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'hash' => 'required|exists:users,hash',
'language' => 'required|in:NLD,FRA',
'title' => 'required',
'firstName' => 'required',
'lastName' => 'required',
'street' => 'required',
'postalCode' => 'required',
'city' => 'required',
'email' => 'required|email',
'birthday' => 'required|date_format:d/m/Y',
'tac' => 'required'
];
}
}
Controller method index.
public function index($hash)
{
$user = $this->user->byHash($hash);
if(is_null($user)) {
return redirect()->to('/');
}
if(! is_null($user->myRelationName)) {
return redirect()->route('thanks');
}
return view('my-view', ['user' => $user]);
}
Controller method store
public function store(RegistrationRequest $request)
{
$user = $this->user->byHash($request->hash);
$user->language = $request->language;
$user->title = $request->title;
$user->firstName = $request->firstName;
$user->lastName = $request->lastName;
$user->street = $request->street;
$user->postalCode = $request->postalCode;
$user->city = $request->city;
$user->email = $request->email;
$user->birthday = $request->birthday;
$user->tac = true;
$user->ip = $this->getRemoteIPAddress();
$user->save();
return redirect()->route('my-route', ['hash' => $request->hash]);
}
Vieuw.blade.php
#extends('layouts.master')
#section('content')
<div class="bottom">
<div class="form-container">
<h2>{{trans('merci.register_maintitle')}}</h2>
<p>{!!trans('merci.register_p1')!!}</p>
<p>{!!trans('merci.register_p2')!!}</p>
<h3>{!!trans('merci.register_h3')!!}</h3>
{{ Form::open(['route' => 'register.store', 'class' => 'form', 'id' => "register-form"]) }}
{{Form::hidden('hash', $user->hash, array("id" => "hash"))}}
<div class="form-field-wrap form-group language {{$errors->has('language') ? 'has-error' : null}}">
{{ Form::label('language', trans('merci.register_language'), array('class' => 'form-field-text-label radio-label'))}}
{{ Form::radio('language', trans('merci.register_language1_value'), ($user->language == trans('merci.register_language1_value')) ? true : false, array('id' => 'nl-rad')) }}
<span>{{trans('merci.register_language1_label')}}</span>
{{ Form::radio('language', trans('merci.register_language2_value') , ($user->language == trans('merci.register_language2_value')) ? true : false, array('class' => 'radio', "id"=> 'fr-rad')) }}
<span>{{trans('merci.register_language2_label')}}</span>
</div>
<div class="form-field-wrap form-group title {{$errors->has('title') ? 'has-error' : null}}">
{{ Form::label('title', trans('merci.register_title'), array('class' => 'form-field-text-label radio-label'))}}
{{ Form::radio('title', trans('merci.register_title1_value'), ($user->title == trans('merci.register_title1_value')) ? true : false) }}
<span>{{trans('merci.register_title1_label')}}</span>
{{ Form::radio('title', trans('merci.register_title2_value'), ($user->title == trans('merci.register_title2_value')) ? true : false, array('class' => 'radio')) }}
<span>{{trans('merci.register_title2_label')}}</span>
</div>
<div class="form-field-wrap form-group lastName {{$errors->has('lastName') ? 'has-error' : null}}">
{{ Form::label('lastName', trans('merci.register_lastName'), array('id' => 'lastName', 'class' => 'form-field-text-label'))}}
{{ Form::text('lastName', $user->lastName, array('class' => 'form-field-text-input')) }}
</div>
<div class="form-field-wrap form-group firstName {{$errors->has('firstName') ? 'has-error' : null}}">
{{ Form::label('firstName', trans('merci.register_firstName') , array('class' => 'form-field-text-label'))}}
{{ Form::text('firstName', $user->firstName, array('class' => 'form-field-text-input')) }}
</div>
<div class="extramargin form-field-wrap form-group street {{$errors->has('street') ? 'has-error' : null}}">
{{ Form::label('street', trans('merci.register_street'), array('class' => 'form-field-text-label'))}}
{{ Form::text('street', $user->street, array('class' => 'form-field-text-input big')) }}
</div>
<div class="smallerpostal form-field-wrap form-group postalCode {{$errors->has('postalCode') ? 'has-error' : null}}">
{{ Form::label('postalCode', trans('merci.register_postalCode'), array('class' => 'form-field-text-label smaller-label'))}}
{{ Form::text('postalCode', $user->postalCode, array('class' => 'form-field-text-input smaller')) }}
</div>
<div class="smallercity form-field-wrap form-group city {{$errors->has('city') ? 'has-error' : null}}">
{{ Form::label('city', trans('merci.register_city'), array('class' => 'form-field-text-label smal-label'))}}
{{ Form::text('city', $user->city, array('class' => 'form-field-text-input smal')) }}
</div>
<div class="extramargin form-field-wrap form-group email {{$errors->has('email') ? 'has-error' : null}}">
{{ Form::label('email', trans('merci.register_email'), array('class' => 'form-field-text-label'))}}
{{ Form::email('email', $user->email, array('class' => 'form-field-text-input ')) }}
</div>
<div class="form-field-wrap form-group birthday {{$errors->has('birthday') ? 'has-error' : null }} ">
{{ Form::label('birthday', trans('merci.register_birthday'), array('class' => 'form-field-text-label', "id" => "birthdate"))}}
{{ Form::text('birthday', $user->birthday, array('class' => 'form-field-text-input', "id"=>"datepicker")) }}
</div>
<div class="check form-field-wrap form-group tac {{$errors->has('tac') ? 'has-error' : null }}">
{{ Form::checkbox('tac', trans('merci.register_tac_value'), false, array('class' => 'form-field-checkbox', "id" => "tac"))}}
{{ Form::label('tac', trans('merci.register_tac_label'), array('class' => 'form-field-error-label')) }}
<span>{!!trans('merci.register_tac_label_link')!!}</span>
</div>
#if (count($errors) > 0)
<div id="error server" style='display:none;'>
#else
<div id="error" style='display:none;'>
#endif
<p class="error">{{trans('merci.register_error')}}</p>
</div>
{!! Form::submit(trans('merci.register_submit'), array('class' => 'btn-main btn')) !!}
{{ Form::close() }}
<small>{{trans('merci.register_mandatory')}}</small>
</div>
</div>
<script src="{{ asset('js/validate.js') }}"></script>
#stop
I don't know if your routes are inside the web middleware, but if you are losing the $errors bag variable, that could be the cause.
Any routes not placed within the web middleware group will not have
access to sessions and CSRF protection (See the default routes file).
When $errors variable is bound to the view by the web middleware group this variable will always be available in your views. (See Displaying The Validation Errors).
// Make sure any routes that need access to session features are placed within
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'MyController#index');
});
Also, I would use the old helper in the blade template to retrieve flashed input from the previous request.
{{ old('username') }}

Form::Model eloquent binding

I'm having problems populating values of my inputs when I have eloquent queries using with(
Controller:
private $viewPath = "pages.person.";
public function edit($id)
{
$person = Person::where('id', '=', $id)->with('Email', 'Phone', 'User', 'Client', 'JuridicPerson.TypeActivities')->firstOrFail();
$this->setData('person', $person); // Set information to be used in the creation of `views` and `nest.views`.
$this->setData('users', User::lists('name', 'id'), ['0' => 'Select…']); // Set information to be used in the creation of `views` and `nest.views`.
return $this->view($this->viewPath.'edit'); // Register a new view.
}
My views are made in a way that I share the form between my edit and my create. So I have create.blade.php, edit.blade.php and both made a call to form.blade.php this I can not change.
My edit.blade
{{ Form::model($person, array('method' => 'PATCH', 'class' => 'defaultForm', 'route' => array('person.update', $person->id))) }}
#include('pages.person.form')
{{ Form::close() }}
My form.blade
<!-- This input brings the correct value -->
<div class="row">
<div class="col-md-12">
{{ Form::input('name', 'name', null, ['class' => 'form-control', 'placeholder' => 'Nome', 'maxlength' => 35, 'required', 'autofocus']) }}
</div>
</div>
<!-- This input value is empty -->
<div class="row">
<div class="col-md-12">
{{ Form::textarea('Client[observation]', null, ['class' => 'form-control', 'placeholder' => 'Observations']) }}
</div>
</div>
But if I add this piece of code anywhere in my html, I get the correct value in client...
{{ $person->client }}
Not sure what should I do to fix my code, the data is correct, when I print the data (above code) the inputs output the correct value (but I can't have the the return printed on the screen for the user).
What I need is to print the correct value into the correct input.
Use client rather than Client when loading that relationship.
When you did {{ $person->client }} it had the side effect of loading that client relationship so it could be used.
When loading relationships, you should use the name of the function, exactly, that's responsible for setting up those relationships.

Laravel 4 Form Submission and Input Retrieval

I am a beginner in Laravel. I am trying to make a simple login form, by using a controller to manipulate the input. However everytime the code just ignore the controller function and keep calling the index everytime I submit. Please advise.
Here is the code for my form
{{ Form::open(array('action' => 'CoverController#authent')) }}
<div class="col-md-3 text-box pull-left">
{{ Form::email('email', '', array('placeholder'=>'Email')); }}
</div>
<div class="col-md-3 text-box pull-left">
{{ Form::password('password', array('placeholder'=>'Password')); }}
</div>
<div class="clearfix"> </div>
<div class="con-button">
{{ Form::submit('Sign Up / Log In'); }}
</div>
{{ Form::close() }}
Below is my routes
Route::get('/',array('as'=>'users','uses'=>'CoverController#index'));
Route::post('/','CoverController#authent');
Here is my controller function
class CoverController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$view = View::make('cover');
return $view;
}
public function authent()
{
$email = Input::get('email');
$pwd = Input::get('password');
$view = View::make('formoid')->with('email',$email)->with('password',$pwd);
return $view;
}
}
With the above code,everytime the login button is pressed, the index() function is called instead of authent(), what am I doing wrong?
Try:
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
Form Doc

Categories