Laravel - How to handle errors on PUT form? - validation

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>

Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Related

Laravel Update DB with array from views

i'm doing a simple project but having some difficulties with updating my database with values that I get from a form. The project is having a list of movies and when you click on one it would take you to a page with more details. Theres a button which you can update the details of that movie. I'm trying save whatever details are made to the relevant index of the table using the id. I can't seem to get it to work though. I did something similar when creating a new entry but having some difficulty updating the values of a specific movie/page. Thanks for any help!
Route:
Route::get('catalog', 'App\Http\Controllers\CatalogController#getIndex');
Route::get('catalog/show/{id}', 'App\Http\Controllers\CatalogController#getShow');
Route::get('catalog/create', 'App\Http\Controllers\CatalogController#getCreate');
Route::get('catalog/edit/{id}', 'App\Http\Controllers\CatalogController#getEdit');
Route::post('catalog/create', 'App\Http\Controllers\CatalogController#postCreate');
Route::put('catalog/edit/{id}','App\Http\Controllers\CatalogController#putEdit');
Controller:
public function getEdit($id)
{
return view('catalog.edit', ['arrayPeliculas' => Movie::all()]);
}
public function getCreate()
{
return view('catalog.create');
}
public function postCreate(Request $request)
{
$Movie = new Movie;
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
public function putEdit(Request $request, $id)
{
$Movie = new Movie;
$Movie[$id]->title = $request->title;
$Movie[$id]->year = $request->year;
$Movie[$id]->director = $request->director;
$Movie[$id]->poster = $request->poster;
$Movie[$id]->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Edit page:
<form method="PUT">
{{ method_field('PUT') }}
{{-- TODO: Protección contra CSRF --}}
{{ csrf_field() }}
<div class="form-group">
<label for="modificar">Modificar Pelicula</label>
<input type="text" name="title" id="title" class="form-control" value="{{ $arrayPeliculas[$id]->title }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el año --}}
<label for="Año">Año</label>
<input type="text" name="year" id="year" class="form-control" value="{{ $arrayPeliculas[$id]->year }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el director --}}
<label for="Director">Director</label>
<input type="text" name="director" id="directo" class="form-control" value="{{ $arrayPeliculas[$id]->director }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el poster --}}
<label for="Poster">Poster</label>
<input type="text" name="poster" id="poster" class="form-control" value="{{ $arrayPeliculas[$id]->poster }}">
</div>
<div class="form-group">
<label for="synopsis">Resumen</label>
<textarea name="synopsis" id="synopsis" class="form-control" rows="3" >{{ $arrayPeliculas[$id]->synopsis }}"</textarea>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" style="padding:8px 100px;margin-top:25px;">
Añadir película
</button>
</div>
</form>
I tried a few other things like->update but I can't seem to get it to work properly.
To update an existing model, first find() it.
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Using the update function should also work then:
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->update([
'title' => $request->title,
'year' => $request->year,
'director' => $request->director,
'poster' => $request->poster,
'synopsis' => $request->synopsis,
]);
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
You could really simplify it with some Laravel magic like Route Model Binding...
Route::put('catalog/edit/{movie}','App\Http\Controllers\CatalogController#putEdit');
...
public function putEdit(Request $request, Movie $movie)
{
$movie->update($request->all());
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}

Laravel 5.7 using same url action for insert and update with #yield in blade template

I am using laravel 5.7 and I am using one form for inserting and updating. In form action I want to use #yield() for laravel route to get the id for updation. Every thing is fine but I can't use #yield() method. Here is my code, problem is only in action of the form.
<form class="form-horizontal" action="{{ url('/todo/#yield('editId')') }}" method="post">
{{csrf_field()}}
#section('editMethod')
#show
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="#yield('editTitle')" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">#yield('editBody')</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
I have also checked with single and double quotes.
action="/todo/#yield('editid')"
When I use simple this method then after submitting it redirects me to localhost and with an error page not found. In laravel 5.4 it works. but not in laravel 5.7. Any help would be appreciated Thanks
Here is my edit.blade.php from where I am using the #section and #yield
#extends('Todo.create')
#section('editId',$item->id)
#section('editTitle',$item->title)
#section('editBody',$item->body)
#section('editMethod')
{{ method_field("PUT") }}
#endsection
Controller store edit and update methods are
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("todo");
}
public function edit($id)
{
$item = todo::find($id);
return view("Todo.edit",compact('item'));
}
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("/todo");
}
To answer the OP actual question you would need to do
#section('editId', "/$item->id") or #section('editId', '/'.$item->id')
{{ url('/todo') }}#yeild('editId')
But much better to do
{{ url('/todo/'.(isset($item) ? $item->id : '')) }}
Or for PHP >= 7
{{ url('/todo/'.($item->id ?? '')) }}
As apokryfos already mentioned - #yield is thought to make reusing your templates easier.
If you simply want to determine (for example) which action should be called afterwards you should better do something like that:
#extends('Todo.create')
<form class="form-horizontal" action="/todo/{{ isset($item) ? $item->id : '' }}" method="post">
#if( ! isset($item))
{{ method_field("PUT") }}
#else
{{ method_field("PATCH") }}
{{csrf_field()}}
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="{{ isset($item) ? $item->title : '' }}" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">{{ isset($item) ? $item->body : '' }}</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
Also as I remember the method field should always come first to make sure it's recognized correctly. Additionally you shouldn't need url() to generate the url I think.
No need for a second blade. Simply inject the variables directly into the template and make sure they are set before you access them. I didn't try it but I'd think that it should work.

I want to display data in textfield. when search data have

I want to display data in textfield . Not all data. When search by name and it have data then went to display data in textfield. And search form and want to display form is same form.
<form action="postAuth" method="post" enctype="multipart/form-data">
<div class="input-group">
<input type="text" class="form-control" name="productname" placeholder="Search Product"> <span class="input-group-btn">
<button type="submit" class="btn btn-default" name="search">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<div class="form-group">
<label for="ProductName" >Product Name :</label>
<input type="text" class="form-control" name="ProductName">
</div>
</form>
route
Route::post("postAuth", ['as' => 'search' , 'uses'=> 'ProductController#postAuth']);
That's my controller
public function postAuth(Request $request)
{
//check submit
$update = $request->get('update',false);
if($update){
return $this->update($request);
}
$productname = $request->input('productname');
$product = DB::table('products')
->where('product_name','LIKE','%'.$productname.'%')
->get();
if($product->count() > 0)
return redirect()->to('/update')->withDetails($product)->withQuery($productname);
else
$request->session()->flash('alert-danger','No Data Found!');
return redirect()->to('/update');
}
can anyone help me please
Here what you exactly want : Just for example
<div class="form-group">
{{Form::label('name', trans('admin.venue.fields.name'),['class' => 'col-md-4 control-label'])}}
<div class="col-md-6">
{{Form::text('name',old('name', isset($venue) ? $venue->name : ''),['class' => 'form-control'])}}
</div>
</div>
Model function example :
public function save(Request $request) {
try {
$this->validate($request, Venue::rules(), Venue::messages());
$venue = Venue::saveOrUpdate($request);
if($venue !== false) {
if($request->get('continue', false)) {
return redirect()->route('admin.venue.edit', ['id' => $venue->id])->with('success', trans('admin.venue.save_success'));
} else {
return redirect()->route('admin.venue.index')->with('success', trans('admin.venue.save_success'));
}
} else {
return back()->with('error', "Unable to save venue")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save venue")->withInput();
}
}
Hope it is useful.
use session() in the value field of ProductName input tag and with some logic, for example
view file:
#if(session()->has('data'))
#if(count(session('data')))
#foreach(session('data') as $data)
<input type="text" class="form-control" name="ProductName" value="{{ $data->prodcut_name }}">
#endforeach
#else
<input type="text" class="form-control" name="ProductName" value="No Data Available">
#endif
#else
<input type="text" class="form-control" name="ProductName">
#endif
and in Controller:
public function postAuth(Request $request) {
$productname = $request->input(productname);
$product_search = Products::where('product_name', $productname)->get();
if($product_search) {
return redirect()->back()->with('data', $product_search);
}
}

Laravel PHPUnit Test Undefined Errors Variable

I would like someone to explain to me why I'm getting undefined variable errors when I run my phpunit tests from my Laravel application. I have if statements set up so that it doesn't add them by default so not sure why.
<?php
Route::auth();
Route::group(['middleware' => 'web'], function () {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'HomeController#dashboard']);
});
<form role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group form-material floating {{ $errors->has('email') ? 'has-error' : '' }}">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}"/>
<label for="email" class="floating-label">Email</label>
#if ($errors->has('email'))
<small class="help-block">{{ $errors->first('email') }}</small>
#endif
</div>
<div class="form-group form-material floating {{ $errors->has('password') ? 'has-error' : '' }}">
<input id="password" type="password" class="form-control" name="password" />
<label for="password" class="floating-label">Password</label>
#if ($errors->has('password'))
<small class="help-block pull-left">{{ $errors->first('password') }}</small>
#endif
</div>
<div class="form-group clearfix">
<div class="checkbox-custom checkbox-inline checkbox-primary checkbox-lg pull-left">
<input type="checkbox" id="inputCheckbox" name="remember">
<label for="inputCheckbox">Remember me</label>
</div>
<a class="pull-right" href="{{ url('/password/reset') }}">Forgot password?</a>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg margin-top-40">Log in</button>
</form>
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends TestCase
{
use WithoutMiddleware;
/** #test */
public function user_can_visit_login_page()
{
$this->visit('login');
}
/** #test */
public function user_submits_form_with_no_values_and_returns_errors()
{
$this->visit('login')
->press('Log in')
->seePageIs('login')
->see('The email field is required.')
->see('The password field is required.');
}
/** #test */
public function it_notifies_a_user_of_wrong_login_credentials()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type('notmypassword', 'password')
->press('Log in')
->seePageIs('login');
}
public function user_submits_login_form_unsuccesfully()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type($user->password, 'password')
->press('Log in')
->seePageIs('dashboard');
}
}
Errors Given
1) LoginTest::user_can_visit_login_page
A request to [http://myapp.app/login] failed. Received status code [500].
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:61
/Users/me/Projects/repositories/MyApp/tests/LoginTest.php:13
Caused by
exception 'ErrorException' with message 'Undefined variable: errors' in /Users/me/Projects/repositories/MyApp/storage/framework/views/cca75d7b87e55429621038e76ed68becbc19bc14.php:30
Stack trace:
Remove the WithoutMiddleware trait from your test.

Laravel 5 how to use get parameter from url with controller's sign in method

I'm trying to implement a login system where the user will be redirect back only if there is a get parameter in the url, else it will be redirect to the profile page.
So, if the uri is something like this (no get parameter)
/login
if success, the user will be redirect to the profile page.
But if the uri has the get parameter like for example
/login?r=articles
the user will be redirected to the articles page instead of the default route to the profile page.
Question is, in the controller, how can do this, if possible, or how can I check for the get parameter?
routes.php
// Signin
Route::post('/account/signin', [
'uses' => 'UserController#postSignIn',
'as' => 'user.signin',
]);
UserController.php
// Signin
public function postSignIn(Request $request)
{
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
// Tried this, isn't working... (maybe something's missing ??)
$redirect = $request->input('r');
if ($redirect) {
return redirect()->route($redirect);
}
// -->
return redirect()->route('user.account');
}
return redirect()->back();
}
signin.blade.php
<form role="form" action="{{ route('user.signin') }}" method="post" class="login-form" name="login">
<div class="form-group {{ $errors->has('login-email') ? 'has-error' : '' }}">
<label class="sr-only" for="email">Email</label>
<input type="text" name="login-email" value="{{ Request::old('login-email') }}" placeholder="Email..." class="form-username form-control" id="form-username">
</div>
<div class="form-group {{ $errors->has('login-password') ? 'has-error' : '' }}">
<label class="sr-only" for="password">Password</label>
<input type="password" name="login-password" value="{{ Request::old('login-password') }}" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<div class="form-group">
<input type="checkbox" name="remember" value="{{ Request::old('remember') }}" id="remember">
Remember
</div>
<button type="submit" class="btn">Sign in!</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Thanks.
Updated
Thank you all for your replies, the fact is that I'm still getting to know Laravel and that's probably why I can't implement it right the solutions that you guys shared.
So this said, I got it working by creating a conditional hidden field that holds the query value and this way once the user submits the form, it will be passed with the rest of the $response arguments.
signin.blade.php
<form role="form" action="{{ route('user.signin') }}" method="post" class="login-form" name="login">
<div class="form-group {{ $errors->has('login-email') ? 'has-error' : '' }}">
<label class="sr-only" for="email">Email</label>
<input type="text" name="login-email" value="{{ Request::old('login-email') }}" placeholder="Email..." class="form-username form-control" id="form-username">
</div>
<div class="form-group {{ $errors->has('login-password') ? 'has-error' : '' }}">
<label class="sr-only" for="password">Password</label>
<input type="password" name="login-password" value="{{ Request::old('login-password') }}" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<div class="form-group">
<input type="checkbox" name="remember" value="{{ Request::old('remember') }}" id="remember">
Remember
</div>
<button type="submit" class="btn">Sign in!</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
<!-- Verify condition -->
#if(isset($_GET['referer']))
<input type="hidden" name="referer" value="{{ $_GET['referer'] }}">
#endif
</form>
UserController.php
// Signin
public function postSignIn(Request $request)
{
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
// Check for the new argument 'referer'
if (isset($request->referer)) {
return redirect()->route($request->referer);
}
// -->
return redirect()->route('user.account');
}
return redirect()->back();
}
Like so, it works.
Don't know if it's a viable and secure way to do it in Laravel 5, but it is working.
When you have an URI such as login?r=articles, you can retrieve articles like this:
request()->r
You can also use request()->has('r') to determine if it's present in the URI.
And request()->filled('r') to find out if it's present in the URI and its value is not empty.
// only query
$query_array = $request->query();
or
$query = $request->query('r');
// Without Query String...
$url = $request->url();
// With Query String...
$url = $request->fullUrl();
If you are using Laravel then use their helper which works just out of the box, i.e. if your route or url has a auth middlewere and user is not logged in then it goes to login and in your postSign or inside attempt just
return redirect()->intended('home'); //home is the fallback if no intended url is provide
UserController
public function postSignIn(Request $request){
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
return redirect()->intended('user.account);
}
return redirect()->back();
}
first use this
use Illuminate\Support\Facades\Input;
then you can get any data from your url
$name=Input::get('term', false); //term is the parameter name we get from URL
If you are still in this quest you can use
Request
like
$request->r

Resources