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.
Related
I am using Laravel framework as a backend API and a few blade PHP files for the front end, specifically for the authentication and the admin panel from the /admin route.
In /admin, I display a list of all registered users and buttons next to them. (This page is only visible for users that have their value in Admin column set as true). I want to toggle the Admin status of a user, either promoting or demoting them by clicking the button next to the user name.
For this, I tried to use a form submit with get method.
I have a method defined inside UserController like this:
public function setAdmin($id) {
$user = User::find($id);
$user->admin = !$user->admin;
if($user->save()) {
echo "Changed";
}
else {
echo "Could not be changed";
}
}
I want to call this method from the view on the click of a button.
I tried using a Form to send a request by specifying the action, but it gave an error saying the values passed are less than the expected number of parameters.
{!! Form::open(['action' => ['UserController#setAdmin', $user->id], 'method' => 'POST']) !!}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
I have a route set up explicitly to call this action
Route::post('/admin/users/setAdmin', 'UserController#setAdmin')
Although I am not sure if I have to set an explicit route for this action or if it's possible to call a controller function directly from a view without defining the route.
I have iterated through User Model to display all users:
#if(count($users) > 0)
#foreach($users as $user)
<div class="card">
{{ $user }}
</div>
{!! Form::open(['action' => ['UserController#setAdmin', $user->id], 'method' => 'POST']) !!}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
#endforeach
#else
<h2>No users found!</h2>
#endif
EDIT: Added the foreach section of the blade file. Also I modified the 'action' part of the Form::open() parameters, it was a mistype, the parameters error is still there.
Can someone explain how this can be done?
You are trying to pass a parameter to your route but there is any within its declaration. You need to add it in your route path:
Route::post('/admin/users/setAdmin/{id}', 'UserController#setAdmin')
If you don't want to have an URL like this, you should add a hidden input to your form containing your ID:
{!! Form::open(['action' => ['UserController#setAdmin'], 'method' => 'POST']) !!}
{{ Form::hidden('id', $user->id) }}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
And in your controller's method:
use Request;
/* ... */
public function setAdmin(Request $request) {
$user = User::find($request->id);
/* ... */
}
I have this code for my form and it works well:
<div class="form-group">
<select class="form-control" id="exampleSelect1">
<option>Assign</option>
#foreach ($projects as $project)
<option>{{ $project->name }} </option>
#endforeach
</select>
</div>
but what I'm trying to do is this with a contact form:
<div class="form-group">
{!! Form::label('name', 'Project') !!}
{!! Form::select (#theforeach with the values :c ) !!}}
</div>
I'm using the use App\Http\Requests\ContactFormRequest; and I have been searching the way of doing it but there is to few examples on google.
Form is part of the Laravel Collective HTML library, you can find the documentation here, specifically you're looking for the Select documentation:
echo Form::select('size', ['L' => 'Large', 'S' => 'Small']);
You have a Collection of Project models, each with a name and (presumably) an id which you need to turn into a key -> value array for the select method which you can do using pluck:
{!! Form::select('project', $projects->pluck('name', 'id')) !!}
Then within your controller you'll be able to find the project that has been selected using find, e.g:
Project::find($request->project);
If you want your select options to works, you need to call it properly,
From controller,
// Example : This is for single view page
$list_of_options = Products::pluck('name','id');
return view('your_view_name',compact('list_of_options'));
// Example : If you want select dropdown in all page ( within the controller views) then,
use Illuminate\Support\Facades\View;
public function __construct(){
View::share('list_of_options',Products::pluck('name','id'));
}
Now in blade,
{{ dd($list_of_options); }} // Check if the values are comming in proper formate
{!! Form::select('name_of_the_select', $list_of_options, null ,[
'class' => 'form-control',
'id' => 'name_of_the_select'
]);
!!}
Here is the button with <i> or <span> inside of it :-
{{ Form::button(
'<span class="fa fa-play fa-1x"></span>',
[
'class'=>'btn btn-info',
'type'=>'button'
])
}}
From your question ( UPDATED )
<div class="form-group">
{!! Form::label('exampleSelect1', 'Project') !!}
{!! Form::select('projects', $projects, null ,[
'class' => 'form-control',
'id' => 'exampleSelect1',
'placeholder' => 'Please select project'
]);
!!}
</div>
I hope this helps. :)
Try this
<div class="form-group">
{!! Form::label('project', 'Project') !!}
{!! Form::select ('project', $projects->pluck('name')) !!}}
</div>
See docs https://laravel.com/docs/4.2/html#drop-down-lists
<div class="form-group">
{!! Form::label('project', 'Project') !!}
{!! Form::select ('project', $projects->pluck('name', 'id')) !!}}
</div>
I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)
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') }}
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') }}