Laravel reset value in input after validation fail? - php

I'm so confuse now, I'm learning Laravel from Laracast, according to the instructor, after validation fail, the form does not reset values that user entered. But when testing validation, when I submit the form reset every thing.
Another question is the undefined variable $errors when I try to access it.
My Controller
<?php
namespace App\Http\Controllers;
use App\Articles;
use App\Http\Requests\CreateArticle;
use Carbon\Carbon;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ArticlesController extends Controller
{
public function create()
{
return view('articles.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
Articles::create($request->all());
return redirect('articles');
}
}
My View
#extends('app')
#section('content')
<h1>Create a new Articles</h1>
<hr/>
{!! Form::open(['url' => 'articles']) !!}
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('body', 'Body') !!}
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('published_at', 'Published On:') !!}
{!! Form::input('text', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('submit', ['class' => 'btn btn-primary']) !!}
</div>
#if(isset($errors))
{{var_dump($errors)}}
#endif
{!! Form::close() !!}
#stop
He use v5.0 and I'm using v5.2

return the following from your controller...
return redirect('articles')->withInput();
see if that helps. you can exclude certain fields if you wanted to like this..
return redirect('articles')->withInput($request->only('email'))

If your are not using
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('title', old('title'), ['class' => 'form-control']) !!}
</div>
but have simple input fields like
<input id="Email" name="Email" type="email" class="uit-input" placeholder="your email address" value={{old('Email')}}>
'prefill' the value with the old data.

There are a couple of issues here.
The first one, the inputs not being saved after validation fails. I believe this is because you are passing null into the functions which are building the inputs when you should be passing in the value you wish it to default to. Try the following...
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('title', old('title'), ['class' => 'form-control']) !!}
</div>
This should then populate the input element with the old data which was previously entered. Just follow the same procedure for the rest of the form inputs.
The second issue with the $errors value not being set is actually due to a change with Laravel 5.2. Many people have been having the same exact issue so I'd just like to refer you to a previous answer: Laravel 5.2 $errors not appearing in Blade

Best way for you
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="upload_title" class="form-control" value="{{ (old('title')) ? old('title') : $data->title}}">
</div>

Related

Multiple values in laravel post form (dropdown)

Good day fellow programmers,
I have been frustrated all day because I have to make a submit form for an hour register app I have to create for the company I'm an intern at.
So basically what has to be done: I have made a submit form with multiple values, I got asked to make a dropdown selection in which I can put the values of "company name" and "task name". (tasks are connected to the company name). So basically what i'm wondering is how I can put 2 values in one dropdown menu. Having the layout of "$company name - $task name"
create.blade.php
{!! Form::open(['url' => 'hoursregistrations/create','files'=>true]) !!}
<div class="form-group" hidden>
{!! Form::label('user_id', 'User ID: ') !!}
{!! Form::text('user_id', $authenticated, null, ['class' => 'form-control']) !!}
</div>
<select name="">
#foreach($items as $item)
<option value="{{ $item->id }}">
{{ $item->company->name }} - {{ $item->name }}
</option>
#endforeach
</select>
<div class="form-group">
{!! Form::label('note', 'Notitie: ') !!}
{!! Form::text('note', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('date', 'Datum: ') !!}
{!! Form::date('date', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('hours', 'Uren: (uren-minuten) ') !!}
{!! Form::time('hours', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<a class="btn btn-danger" href="{{ route('hoursregistrations.index') }}">
#lang('button.cancel')
</a>
<button type="submit" class="btn btn-success">
#lang('button.save')
</button>
</div>
</div>
{!! Form::close() !!}
In this code snippet the company variable is $project_id and the task id is $subproject_id.
Also the controller function to redirect the data to the create view
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$authenticated = Sentinel::getUser()->id;
$activity_name = Subproject::pluck('id');
$items = array(
'company_name' => Company::where('status','client')->pluck('company_name', 'id'),
'subproject_id' => Subproject::pluck('title', 'id')
);
//dd($items);
return view('hoursregistrations.create', compact('subproject_id', 'authenticated',
'company_name', 'activity_name', 'items'));
}
Conclusion: How can I combine the $project_id and $subproject_id into ONE dropdown item.
p.s I'm sorry if it sounds vague I am bad at explaining things
Do you have to use The Form Facade? Although this may not be helpfull to you, you can write it as plain HTML with Blade's Syntax:
<select name="">
#foreach($tasks as $task)
<option value="{{ $task->id }}">
{{ $task->company->name }} - {{ $task->name }}
</option>
#endforeach
</select>

Laravel date input field default time value

I am trying to display a default time value within an input field. For some reason the current time is showing up in my source code but is not displayed in my view.
My Form:
<div class="form-group">
{!! Form::label('published_at', 'Publish On') !!}
{!! Form::input('date','published_at', Carbon\Carbon::now()->format('H:i'), ['class' => 'form-control']) !!}
</div>
Sourcecode:
<div class="form-group"> <label for="published_at">Publish On</label>
<input class="form-control" name="published_at" type="date" value="15:58" id="published_at">
</div>
What's wrong here? I am trying to get the current time and date.

Laravel 5 On POST Status 302 Found

I'm trying to create new post useing laravel , ajax and s3 , But every time i try submit the form i get Status Code:302 Found , I Hope really some help me
Firebug
Here in firebug result image
META
<meta name="csrf" value="{{ csrf_token() }}">
VIEW
The form view with csrf token
<div class="col-md-8 col-md-offset-2">
{!! Form::open(array(
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true
)) !!}
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
<label for="cats">Select Category list :</label>
<select class="form-control" id="category" name="category">
<option value="">Select Category</option>
#foreach($category as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="cats">Select Subcategory list :</label>
<select class="form-control" id="subcategory" name="subcategory">
<option value=>Select Subcategory</option>
<option value=""></option>
</select>
</div>
<div class="form-group">
{!! Form::label('image', 'Upload Image') !!}
{!! Form::file('image', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Description: ') !!}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Your Email: ') !!}
{!! Form::text('email', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Post Free Ad', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
CONTROLLER
First valid the requist and than create new email for the user if he did't have and than save the post with the user
public function storePostAds(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'image' => 'required',
'category_id' => 'required',
'subcategory_id' => 'required',
]);
$email = $request['email'];
$title = $request['title'];
$description = $request['description'];
$category = $request['category_id'];
$subcategory = $request['subcategory_id'];
$image = $request->file('image');
$user = User::where('email', $email)->first();
if(!$user){
$user = new User();
$user->email = $email;
$user->save();
}
if($image->isValid()){
$name = $image->getClientOriginalName();
$key = 'images/'.$name;
Storage::disk('s3')->put($key, file_get_contents($image));
}
$post = new Post();
$post->title = $title;
$post->description = $description;
$post->category_id = $category;
$post->subcategory_id = $subcategory;
$post->image = $image;
$user->posts()->save($post);
return redirect('/');
}
Ajax
ajax to get subcategory foreach category after select
(function($){
$('#category').on('change', function(e){
var cat_id = e.target.value;
$.get('/ajax-subcategory?cat_id=' + cat_id, function(data){
var subcategory = $('#subcategory');
subcategory.empty();
$.each(data, function(index, subcatObj){
subcategory.append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
});
});
}(jQuery));
The name of your category and subcategory fields are "category" and "subcategory" but are being referred to as "category_id" and "subcategory_id" respectively in your Controller code.
In case anyone else had my issue, when first creating your fields on the model, your fields may be required. if the controller is not built correctly, instead of errors it returns 302 on the post response. Try checking you enter data for all the form fields before submitting the form.

Merging laravel's Form class with Bootstraps form-group class

I have a form in laravel to edit a post using bootstrap:
#section('content')
<form method="PUT" action="{{ URL::route('post.update', array($post->id)) }}">
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" id="usr" name="title" value="{{$post->title}}">
<br>
<label for="comment">Details:</label>
<textarea class="form-control" rows="5" id="comment" name="detail"
placeholder="Write a new post.">"{{$post->message}}"</textarea>
<input type="hidden" name="id" value="add">
</div>
Cancel
<div class="pull-right">
<input type="submit" class="btn btn-success" value="Update">
</div>
</form>
#stop
It looks like this:
Now, if I use Laravel's Form class, it's much smaller and neater:
{{Form::model($post, array('method' => 'PUT', 'route' => array('post.update', $post->id)))}}
{{ Form::label('title', 'Post Title: ') }}
{{ Form::text('title') }}
{{ $errors->first('title') }}
<p></p>
{{ Form::label('message', 'Post Message: ') }}
{{ Form::text('message') }}
{{ $errors->first('message') }}
<p></p>
{{ Form::submit('Update') }}
{{ Form::close() }}
However, this causes the form to look quite ugly:
So, in short, is there anyway to use Laravel's form class and add boostrap styling/buttons to it? I want the functionality and easy of use of the form class with the visuals of bootstrap.
You need to add the class to each input (here is an exemple)
{{Form::model($post, array('method' => 'PUT', 'route' => array('post.update', $post->id)))}}
{!! Form::label('title','Post Title: ', array('class' => 'pull-left')) !!}
{!! Form::text('title', null, ['class' => 'form-control'])!!}
{!! Form::label('message','Post Message: ', array('class' => 'pull-left')) !!}
{!! Form::textarea('message', null, ['class' => 'form-control'])!!}
<br>
Cancel
{!! Form::submit('Update', ['class' => 'btn btn-success pull-right']) !!}
{!! Form::close() !!}

Laravel use same form for create and edit

Am quite new to Laravel and I have to create a form for create and a form for edit. In my form I have quite some jquery ajax posts. Am wondering whether Laravel does provide for an easy way for me to use the same form for my edit and create without having to add tons of logic in my code. I don't want to check if am in edit or create mode every time when assigning values to fields when the form loads. Any ideas on how I can accomplish this with minimum coding?
I like to use form model binding so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user model for example):
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{-- More fields... --}}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
So, for example, from a controller, I basically use the same form for creating and updating, like:
// To create a new user
public function create()
{
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user (load to edit)
public function edit($id)
{
$user = User::find($id);
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Pretty easy in your controller you do:
public function create()
{
$user = new User;
$action = URL::route('user.store');
return View::('viewname')->with(compact('user', 'action'));
}
public function edit($id)
{
$user = User::find($id);
$action = URL::route('user.update', ['id' => $id]);
return View::('viewname')->with(compact('user', 'action'));
}
And you just have to use this way:
{{ Form::model($user, ['action' => $action]) }}
{{ Form::input('email') }}
{{ Form::input('first_name') }}
{{ Form::close() }}
For the creation add an empty object to the view.
return view('admin.profiles.create', ['profile' => new Profile()]);
Old function has a second parameter, default value, if you pass there the object's field, the input can be reused.
<input class="input" type="text" name="name" value="{{old('name', $profile->name)}}">
For the form action, you can use the correct endpoint.
<form action="{{ $profile->id == null ? '/admin/profiles' : '/admin/profiles/' . $profile->id }} " method="POST">
And for the update you have to use PATCH method.
#isset($profile->id)
{{ method_field('PATCH')}}
#endisset
Another clean method with a small controller, two views and a partial view :
UsersController.php
public function create()
{
return View::('create');
}
public function edit($id)
{
$user = User::find($id);
return View::('edit')->with(compact('user'));
}
create.blade.php
{{ Form::open( array( 'route' => ['users.index'], 'role' => 'form' ) ) }}
#include('_fields')
{{ Form::close() }}
edit.blade.php
{{ Form::model( $user, ['route' => ['users.update', $user->id], 'method' => 'put', 'role' => 'form'] ) }}
#include('_fields')
{{ Form::close() }}
_fields.blade.php
{{ Form::text('fieldname1') }}
{{ Form::text('fieldname2') }}
{{ Form::button('Save', ['type' => 'submit']) }}
Simple and clean :)
UserController.php
public function create() {
$user = new User();
return View::make('user.edit', compact('user'));
}
public function edit($id) {
$user = User::find($id);
return View::make('user.edit', compact('user'));
}
edit.blade.php
{{ Form::model($user, ['url' => ['/user', $user->id]]) }}
{{ Form::text('name') }}
<button>save</button>
{{ Form::close() }}
For example, your controller, retrive data and put the view
class ClassExampleController extends Controller
{
public function index()
{
$test = Test::first(1);
return view('view-form',[
'field' => $test,
]);
}
}
Add default value in the same form, create and edit, is very simple
<!-- view-form file -->
<form action="{{
isset($field) ?
#route('field.updated', $field->id) :
#route('field.store')
}}">
<!-- Input case -->
<input name="name_input" class="form-control"
value="{{ isset($field->name) ? $field->name : '' }}">
</form>
And, you remember add csrf_field, in case a POST method requesting. Therefore, repeat input, and select element, compare each option
<select name="x_select">
#foreach($field as $subfield)
#if ($subfield == $field->name)
<option val="i" checked>
#else
<option val="i" >
#endif
#endforeach
</select>
Instead of creating two methods - one for creating new row and one for updating, you should use findOrNew() method. So:
public function edit(Request $request, $id = 0)
{
$user = User::findOrNew($id);
$user->fill($request->all());
$user->save();
}
Article is a model containing two fields - title and content
Create a view as pages/add-update-article.blade.php
#if(!isset($article->id))
<form method = "post" action="add-new-article-record">
#else
<form method = "post" action="update-article-record">
#endif
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="Enter title" name="title" value={{$article->title}}>
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" rows="5" id="content" name="content">
{{$article->content}}
</textarea>
<span class="text-danger">{{ $errors->first('content') }}</span>
</div>
<input type="hidden" name="id" value="{{{ $article->id }}}">
<button type="submit" class="btn btn-default">Submit</button>
</form>
Route(web.php): Create routes to controller
Route::get('/add-new-article', 'ArticlesController#new_article_form');
Route::post('/add-new-article-record', 'ArticlesController#add_new_article');
Route::get('/edit-article/{id}', 'ArticlesController#edit_article_form');
Route::post('/update-article-record', 'ArticlesController#update_article_record');
Create ArticleController.php
public function new_article_form(Request $request)
{
$article = new Articles();
return view('pages/add-update-article', $article)->with('article', $article);
}
public function add_new_article(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
Articles::create($request->all());
return redirect('articles');
}
public function edit_article_form($id)
{
$article = Articles::find($id);
return view('pages/add-update-article', $article)->with('article', $article);
}
public function update_article_record(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
$article = Articles::find($request->id);
$article->title = $request->title;
$article->content = $request->content;
$article->save();
return redirect('articles');
}
In Rails, it has form_for helper, so we could make a function like form_for.
We can make a Form macro, for example in resource/macro/html.php:
(if you don't know how to setup a macro, you can google "laravel 5 Macro")
Form::macro('start', function($record, $resource, $options = array()){
if ((null === $record || !$record->exists()) ? 1 : 0) {
$options['route'] = $resource .'.store';
$options['method'] = 'POST';
$str = Form::open($options);
} else {
$options['route'] = [$resource .'.update', $record->id];
$options['method'] = 'PUT';
$str = Form::model($record, $options);
}
return $str;
});
The Controller:
public function create()
{
$category = null;
return view('admin.category.create', compact('category'));
}
public function edit($id)
{
$category = Category.find($id);
return view('admin.category.edit', compact('category'));
}
Then in the view _form.blade.php:
{!! Form::start($category, 'admin.categories', ['class' => 'definewidth m20']) !!}
// here the Form fields
{{!! Form::close() !!}}
Then view create.blade.php:
#include '_form'
Then view edit.blade.php:
#include '_form'
You can use form binding and 3 methods in your Controller. Here's what I do
class ActivitiesController extends BaseController {
public function getAdd() {
return $this->form();
}
public function getEdit($id) {
return $this->form($id);
}
protected function form($id = null) {
$activity = ! is_null($id) ? Activity::findOrFail($id) : new Activity;
//
// Your logic here
//
$form = View::make('path.to.form')
->with('activity', $activity);
return $form->render();
}
}
And in my views I have
{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}
Here is simple way to create or edit record using same form .
I have created form.blade.php file for create and edit
#extends('layouts.admin')
#section('content')
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Create User</h6>
</div>
<div class="card-body">
<form method="post" action="{{isset($user)? route('users.update',$user->id):route('users.store')}}">
#csrf
#if (isset($user))
#method('PUT')
#endif
<div class="row mb-3">
<div class="col-md-4">
<label>Name</label>
<input class="form-control #error('name') is-invalid #enderror" value="{{isset($user->name) ? $user->name: old('name')}}" type="text" name="name" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-4">
<label>Email address</label>
<input class="form-control #error('email') is-invalid #enderror" value="{{isset($user->email) ? $user->email:old('email')}}" type="email" name="email" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-4">
<label>Password</label>
<input class="form-control #error('password') is-invalid #enderror" value="{{old('password')}}" type="text" name="password" required>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-3">
<button class="btn btn-sm btn-success btn-icon-split">
<span class="text">Save</span>
</button>
<a href="{{route('users.index')}}" class="btn btn-sm btn-dark btn-icon-split">
<span class="text">Cancel</span>
</a>
</div>
</form>
</div>
</div>
#endsection
And in my controller
public function create()
{
return view('admin.user.form');
}
public function edit($id){
$user= User::find($id);
return view('admin.user.form', compact('user'));
}
UserController.php
use View;
public function create()
{
return View::make('user.manage', compact('user'));
}
public function edit($id)
{
$user = User::find($id);
return View::make('user.manage', compact('user'));
}
user.blade.php
#if(isset($user))
{{ Form::model($user, ['route' => ['user.update', $user->id], 'method' => 'PUT']) }}
#else
{{ Form::open(['route' => 'user.store', 'method' => 'POST']) }}
#endif
// fields
{{ Form::close() }}
I hope this will help you!!
form.blade.php
#php
$name = $user->name ?? null;
$email = $user->email ?? null;
$info = $user->info ?? null;
$role = $user->role ?? null;
#endphp
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('role', 'Função') !!}
{!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('info', 'Informações') !!}
{!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>
<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>
create.blade.php
#extends('layouts.app')
#section('title', 'Criar usuário')
#section('content')
{!! Form::open(['action' => 'UsersController#store', 'method' => 'POST']) !!}
#include('users.form')
<div class="form-group">
{!! Form::label('password', 'Senha') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Confirmação de senha') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}
#endsection
edit.blade.php
#extends('layouts.app')
#section('title', 'Editar usuário')
#section('content')
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
#include('users.form', compact('user'))
{!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Editar senha
#endsection
UsersController.php
use App\User;
Class UsersController extends Controller {
#...
public function create()
{
return view('users.create';
}
public function edit($id)
{
$user = User::findOrFail($id);
return view('users.edit', compact('user');
}
}
use any in the route
Route::any('cr', [CreateContent::class, 'create_content'])
->name('create_resource');
in controller use
User::UpdateOrCreate([id=>$user->id], ['field_name'=>value, ...]);

Categories