I have a problem with validation rule in edit form. My form fields are name, email, password and password_confirmation. My UpdateUserRequest class return this rules:
return [
'name' => ['required', 'max:50', 'min:3'],
'email' => ['required', 'email', 'unique:users,email,' .$this->route('users')],
'password' => ['required_with:password_confirmation', 'confirmed']
];
And update method in UsersController is:
public function update(Requests\UpdateUserRequest $request, $id)
{
$user = $this->users->findOrFail($id);
$user->fill($request->only('name', 'email', 'password'))->save();
return redirect(route('backend.users.edit', $user->id))->with('status', 'User has been updated.');
}
And this is a form:
{!! Form::model($user, [
'method' => $user->exists ? 'put' : 'post',
'route' => $user->exists ? ['backend.users.update', $user->id] : ['backend.users.store']
]) !!}
<div class="form-group">
{!! Form::label('name') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email') !!}
{!! Form::email('email', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password_confirmation') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>
{!! Form::submit($user->exists ? 'Save User' : 'Create New User', ['class' => 'btn btn-primary btn-sm']) !!}
Password validate rule required_with:password_confirmation should allow user to leave empty fields password and password_confirmation if he does not want to change it, but this doesn't work. When I leave the field empty, the empty value is hashed and stored in database. All other validations work fine, but not when user leaves empty value in password and password_confirmation. Why this isn't working? What am I doing wrong?
You will need to updated the db seperate without using fill etc as it will always get the password value empty or not and then add it, so try:
$user = $this->users->findOrFail($id);
$user->name = $request->get('name');
$user->email = $request->get('emil');
if(!empty($request->get('password')) {
$user->password = $request->get('password');
}
$user->save();
Something like that so you are checking if the PW needs to also be updated etc.
Basically you need to verify if it need to be entered or not, your method takes all the requested values and will update no matter if they are empty or note.
Related
I'm trying to update an edit to a post without using the resource. I tried parsing the variable from my Form to my route using {id} but it gets ignored. This is the form I'm trying to post from.
{!! Form:: open(['action'=> ['ManageBooksController#updateBook', $book->id], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('Book_NAME', 'Name')}}
{{Form::text('Book_NAME', $book->Book_NAME, ['class' => 'form-control', 'placeholder' => 'Name'])}}
</div>
{{Form::hidden('_method', PUT)}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!!Form:: close() !!}
This is my route
Route::put('manageBooks', 'ManageBooksController#updateBook');
This is my method in my controller
public function updateBook(Request $request, $id)
{
$this->validate($request, ['Book_NAME' => 'required']);
$books = Books::find($id);
$books->Book_NAME =$request->input('Book_NAME');
$books->save();
return redirect('/manageBook')->with('success', 'Book Edited');
}
Your route is expecting a PATCH. Try updating your route to:
Route::post('/manageBooks/{id}', 'ManageBooksController#updateBook');
Or include the Laravel's #method('PATCH') within your form.
Also, your controller names don't match :)
Consider changing sequence of the arguments to the function:
public function updateBook($id, Request $request) // Notice the sequence of the arguments
{
......
}
If you want to use Route, you have to specifics like this
{!! Form:: open(['route'=> ['manage_book', $book->id], 'method' => 'POST']) !!}
In your route, you may need to name it properly
Route::post('/manageBooks/{id}', array('as'=>'manage_book','uses'=>'ManageBooksController#updateBook'));
Hope it helps.
Update without using resource :
your route :
Route::get('/manageBooks', 'ManageBooksController#whateverer')->name('manageBooks');
Route::post('/manageBooks/{id}/edit', 'ManageBooksController#updateBook')->name('updateBook');
your blade:
{!! Form:: open(['route'=> ['updateBook', $book->id], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('Book_NAME', 'Name')}}
{{Form::text('Book_NAME', $book->Book_NAME, ['class' => 'form-control', 'placeholder' => 'Name'])}}
</div>
{{Form::hidden('id', $book->id)}} //hidden field is not required
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!!Form:: close() !!}
your controller:
public function updateBook(Request $request, $id)
{
$this->validate($request, ['Book_NAME' => 'required']);
$books = Books::where('id',$id)->update(['Book_NAME'=>$request->Book_NAME]);
return redirect()->route('manageBooks')->with('success', 'Book Edited');
}
In the end I added another hidden field where i parse the ID through of the post I'm editing. I also changed the find method to take the request variable pointing to the ID.
My Form:
{{Form::hidden('Book_ID', $book->Book_ID)}}
{{Form::hidden('_method', PUT)}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!!Form:: close() !!}
My function:
public function updateBook(Request $request)
{
$this->validate($request, ['Book_NAME' => 'required']);
$books = Books::find($request->Book_ID);
$books->Book_NAME =$request->input('Book_NAME');
$books->save();
return redirect('/manageBook')->with('success', 'Book Edited');
}
Change your method POST to PUT in your from first,
{!! Form:: open(['action'=> ['ManageBooksController#updateBook', $book->id],'method' => 'PUT']) !!}
<div class="form-group">
{{Form::label('Book_NAME', 'Name')}}
{{Form::text('Book_NAME', $book->Book_NAME, ['class' => 'form-control', 'placeholder' => 'Name'])}}
</div>
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!!Form:: close() !!}
Then You Have to Pass a parameter in your route, as your method expecting $id
Route::put('manageBooks/{id}/update', 'ManageBooksController#updateBook');
I am trying to check if the image that i am trying to upload is getthing processed, but when i try to use de Input::hasFile('upimg') to check it out it doesnt do anything. This is my form:
{!! Form::open(array('route' => array('uploadimage'), 'method' => 'POST')) !!}
{!! csrf_field() !!}
<div class="form-group">
{!! Form::label('newimg', 'Choose Image to upload:', ['class' => 'control-label']) !!}
{!! Form::file('upimg', null) !!}
</div>
<div class="form-group">
{!! Form::label('directory', 'Choose directory:', ['class' => 'control-label']) !!}
{!! Form::select('newimage', [ '' => 'none'] + $imagesdir , '', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Upload', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
And this is the code i am using to check the file:
public function doUpload()
{
if (Input::hasFile('upimg')){
echo 'uploaded';
};
}
As you can see i am trying to check:
{!! Form::file('upimg', null) !!}
If i am not wrong its suppose to give mi back the echo but nothing happens. Why is this not working? what am i doing wrong?
Be sure you have an 'file' => true option in your form definition like below:
{!! Form::open(['route' => ['uploadimage'], 'file' => true]) !!}
This option causes that your form will be render with enctype="multipart/form-data" option in HTML form tag. See documentation: HTML enctype
You don't have to add method => 'POST' to your definition of form, because Laravel 5 sents forms with POST method by default.
Please let me know if this solution will not work for you.
For checking files on server side you can use methods of Request object like in documentation of Laravel: Files in Laravel
This is a strange problem i've run into. I have a form that takes in First, Last, Title, Email, and Phone which takes that data and inputs into a ContactPerson table I have set up in a database.
When I fill out the form, and hit submit, only the Title, Email, and Phone number get inserted correctly into the database. The first and last names get inserted as NULL.
Here's some of my code that I have using PHPstorm and Laravel 2.5.3
My Create a New Contact view:
<h1 style="text-align:center;">Add A New Contact Person</h1>
<hr/>
{!! Form::open(['url' => '/create']) !!}
<span style="text-align:center;align-content:right;display:block; margin-right:auto;margin-left:auto;">
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('Title', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('email', 'Email: ') !!}
{!! Form::text('Email', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('phone', 'Phone: ') !!}
{!! Form::text('Phone', null, ['class' => 'form']) !!}
</div>
{!! Form::submit('Submit', ['class' => 'btn btn-primary form']) !!}
</span>
{!! Form::close() !!}
Here is my controller called ResourceController I have created:
class ResourceController extends Controller
{
public function resource()
{
$contacts = ContactPerson::all();
return view('pages.resource', compact('contacts'));
}
public function create()
{
return view('pages.create');
}
public function store(Requests\CreateNewContactRequest $request)
{
ContactPerson::create($request->all());
return redirect('resource');
}
}
Here's the validation I have set up in the CreateNewContactRequest class for the form:
public function rules()
{
return [
'First' => 'required|min:2',
'Last' => 'required|min:1',
'Title' => 'required|min:2',
'Email' => 'required|Email|unique:users',
'Phone' => 'required|numeric|min:9'
];
}
Here's what it looks like when I fill out/submit the form.
After hitting submit it redirects to the database dump:
the view of the database after insertion:
Looking at your dump details, your field names need to match your form names or visa versa, so your form names need to change to say:
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First_Name', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last_Name', null, ['class' => 'form']) !!}
</div>
EG for field name First_Name your input needs to be named the same name="First_Name"
Also making sure your fillable details are also correct
protected $fillable = ['First_Name','Last_Name','Title','Email','Phone'];
In the admin area of my app, I want to have a form by which an admin can find a project by its id and show the project details there. What is the best approach to implement this?
This is what I have tried:
//route
Route::get('admin/projects/{project_id}', 'AdminController#showProject');
//form
{!! Form::open(['action' => 'AdminController#showProject', 'method' => 'get']) !!}
{!! Form::label('project_id', 'Project Id', ['class' => 'control-label']) !!}
{!! Form::text('project_id', null, ['class' => 'form-control']) !!}
{!! Form::submit('Submit', ['class' => 'form-control']) !!}
{!! Form::close() !!}
//controller method
public function showProject(Request $request)
{
$project=Project::find($request->get('project_id'));
return view('admin.projects.showProject', compact('project'));
}
It almost worked but there is little problem. After retrieving the requested project, the ULR is like this:
admin/projects/%7Bproject_id%7D?project_id=5
I want it be like this one:
admin/projects/5
How can I solve this problem?
Create the following routes:
Route::get('admin/projects', 'AdminController#getProject');
Route::post('admin/projects', 'AdminController#postProject');
Route::get('admin/projects/{project_id}', 'AdminController#showProject');
In your getProject function you return a view that show the form where the user can enter an ID. (The one you already have):
{!! Form::open(['action' => 'AdminController#postProject', 'method' => 'post']) !!}
{!! Form::label('project_id', 'Project Id', ['class' => 'control-label']) !!}
{!! Form::text('project_id', null, ['class' => 'form-control']) !!}
{!! Form::submit('Submit', ['class' => 'form-control']) !!}
{!! Form::close() !!}
In your postProject function you just send a redirect to admin/project/{project_id} URL:
public function postProject(Request $request)
{
return redirect('admin/projects/' . $request->project_id);
}
In your showProject function you just retrieve the record and return a view with the information:
public function showProject($ProjectID)
{
$project=Project::find($ProjectID);
return view('admin.projects.showProject'),
->with('Project', compact('project'));
}
Try changing your controller method to
public function showProject($project_id)
{
$project=Project::find($project_id);
return view('admin.projects.showProject', compact('project'));
}
You don't need to use request on get route.
I am thinking of making a landing page from the home page, which will direct the guest to the register page. I thought of making two forms for sending data and two submit buttons in them, let's say reader and writer and according to the button they use to go to the register form page, I want to pass the profession string from the button in the landing page and then, place it into the register form in /auth/register.
{!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}
{!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}
{!! Form::open(array('url' => '/auth/register', 'profession' => 'reader')) !!}
{!! Form::submit('Reader', array('class' => 'btn btn-default')) !!}
{!! Form::close() !!}
It is not directing me to the page app.com/auth/register. But it works when I directly type the link.
What I thought was using $profession in /auth/register/ and access the value and use it as a hidden field in the registeration form.
(using laravel 5.1)
Edit:
In view source:
<form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="writer"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">
<input class="btn btn-warning" type="submit" value="Writer">
</form>
<form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="reader"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">
<input class="btn btn-default" type="submit" value="Reader">
</form>
Edit 2:
{!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}
{!! link_to('/auth/register', 'Writer', array('class' => 'btn btn-default')) !!}
{!! Form::close() !!}
I tried this instead. At least, now it is directing the page but I still can't access the data value of profession
Edit 3:
Routes:
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
Route::get('/', function()
{
return view('pages.home');
});
and https://app.com/auth/register is working.
Here's a step by step walkthrough on how to implement it. I tested it. So it works. This is for 'writer', but you could replicate it as you had originally planned for other professions.
I assume you've registered the Laravel Collective package since you're using the curly braces and exclamation points.
Step 1:
In your landing page view, where you have the writer button, add a hidden field with the string 'writer'. Like this:
{!! Form::open(['route' => ['writer_path']]) !!}
{!! Form::hidden('profession', 'writer') !!}
{!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}
Not that in the open field we are using a named route ('writer_path').
Step 2:
Register a route and a controller on your routes.php file, like this:
Route::post('auth/register', [
'as' => 'writer_path',
'uses' => 'SampleController#displayForm'
]);
Step 3:
In your sample controller, you define the displayForm method.
Within that method you first obtain the value you passed from the landing page view.
If you don't know how to create a controler, you can do
php artisan make:controller SampleController
from the command line
Because the value arrives as an array, you have to obtain the string 'writer' from the array and then pass it to the new view (the view with the registration form for the writer).
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class SampleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function displayForm()
{
$input = Input::get();
$profession = $input['profession'];
return view('writerregistration', ['profession' => $profession]);
}
}
Last Step:
In the new view which you will create as writerregistration.blade.php, you will display the form with the field you just passed ('profession') which contains the string 'writer'. Like this:
{!! Form::open() !!}
{!! Form::label('username', 'Username:') !!}
{!! Form::text('username', null, ['class' => 'form-control']) !!}
{!! Form::label('profession', 'Profession:') !!}
{!! Form::text('profession', $profession, ['class' => 'form-control']) !!}
{!! Form::label('email', 'Email:') !!}
{!! Form::text('email', null, ['class' => 'form-control']) !!}
{!! Form::label('passowrd', 'Password:') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
{!! Form::label('password_confirmation', 'Password Confirmation:') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
{!! Form::submit('Sign Up', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Presto, you've populated the field in the registration form for the writer with the info on the hidden field that belonged to the writer button in the landing page.