I want to display an error in a form, but it cannot be checked via validation.
Blade
<form action="/githubuser" methode="GET">
<div class="error">{{ $errors->first('CustomeError') }}</div>
<input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
#if($errors->has('userName'))
<div class="error">{{ $errors->first('userName') }}</div>
#endif
<input type="submit" value="SUBMIT">
</form>
The Problem is that I start an api call after validation. and if I don't get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.
Controller
public function show(Request $request)
{
$rules = ['userName' => 'required'];
$validator = \Validator::make($request->input(), $rules);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
$data = $this->gitHubUserService->getUserData($request->input('userName'));
/* User on Github not Found **/
if (! $data) {
// >>> THE LINE BELOW IS MY PROBLEM! <<<
return view('form')->withErrors($validator);
}
// ....
}
At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.
Is this possible? Thanks in advance!
The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:
if(! $data){
$validator->errors()->add('customError', 'Github User not found!');
return view('form')->withErrors($validator);
}
Related
I was facing this problem of missing parameter when trying to pass a parameter from one controller to another controller. The parameter is $id whereby the data is originally from post method in details blade.php into function postCreateStepOne However, I want to pass the data into a new view and I return
redirect()->route('details.tenant.step.two')->with( ['id' => $id]
);}
And this is where error occur. However, it works fine if I skip it into a new route and directly return into a view with the compact parameter. For Example,
return view('document.details-step-two', compact('id', 'property'));
However, I would prefer a new url as I was doing multistep form using Laravel.
Error
web.php
Route::get('/document/details/viewing/{id}', 'ViewDetails')->name('details.tenant');
Route::post('/document/details/viewing/{id}', 'postCreateStepOne')->name('post.step-one');
Route::get('/document/details/viewing/step-2/{id}', 'ViewDetailsStep2')->name('details.tenant.step.two');
TenanatController.php
public function viewDetails($id){
$view = Properties::findOrFail($id);
return view('document.details', compact('view'));
}
public function ViewDetailsStep2(Request $request, $id){
$view = Properties::findOrFail($id);
$property = $request->session()->get('property');
return view('document.details-step-two', compact('view', 'property'));
}
public function postCreateStepOne($id, Request $request)
{
$validatedData = $request->validate([
'property-name' => 'required',
]);
if(empty($request->session()->get('property'))){
$property = new Tenancy();
$property->fill($validatedData);
$request->session()->put('property', $property);
}else{
$property = $request->session()->get('property');
$property->fill($validatedData);
$request->session()->put('property', $property);
}
return redirect()->route('details.tenant.step.two')->with( ['id' => $id] );
}
details.blade.php
<form action="{{ route('post.step-one', $view->id) }}" method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="title">Property Name:</label>
<input type="text" value="" class="form-control" id="property-name" name="property-name">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</form>
When you use with on a redirect the parameter is passed through the session. If you want to redirect to a route with a given route parameter you should pass that parameter in the route function itself like e.g.
return redirect()->route('details.tenant.step.two', ['id' => $id]);
Error messages are not showing.I added the redirection in
sendFailedLoginResponse it is redirecting to the login page without error messages
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->route("login")->withErrors([
$this->username() => [trans('auth.failed')],
]);
}
Blade
<div class="form-group col-md-12">
<input id="email" name="email" class="" type="email" placeholder="Your Email">
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
return redirect()->route("login")->withErrors(['email' => trans('auth.failed')]);
Instead of array pass a message bag object like this.
$errors = new Illuminate\Support\MessageBag;
$errors->add('email', trans('auth.failed'));
return redirect()->route("login")->withErrors($errors);
The name of the input field should be the second argument of the withErrors() function.
Laravel documentation - Manually Creating Validators
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->route("login")->withErrors(trans('auth.failed'), 'login');
}
Blade file
<div class="form-group col-md-12">
<input id="email" name="email" class="" type="email" placeholder="Your Email">
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->login->first('email') }}</strong>
</span>
#endif
If Your application is too large folow these steps
While You are making the validation there are several ways
Method one
Using Validator Facade
public function store(Request $request)
{
$input = $request->all();
$validator = \Validator::make($input, [
'post_name' => 'required',
'post_type' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput($input);
}
Post::create($input);
return redirect('post.index');
}
Method Two
using $this->validate(); Method
public function store(Request $request)
{
$this->validate($request, [
'post_name' => 'required',
'post_type' => 'required',
]);
Post::create($request->all());
}
Method Three
Using the request method
php artisan make:request PostStoreRequest
anf the file will be creted in app\Http\Requests with name PostStoreRequest.php
open you controller and add
use App\Http\Requests\PostStoreRequest;
now the file contents
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostStoreRequest extends FormRequest
{
/**
* 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 [
'post_name' => 'required',
'post_type' => 'required',
];
}
/**
* Custom message for validation
*
* #return array
*/
public function messages()
{
return [
'post_name.required' =>'Enter Post Name',
'post_type.required' =>'Enter Post Type',
];
}
}
if You want to customize the error message use messages function
now the store function
public function store(PostStoreRequest $request)
{
Post::create($request->all() );
return redirect()->route('post.index')->with('success','CrmHfcImageGallery Created Successfully');
}
now Comming to the view
to view all the messages add this in top of the blade file
#if ($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
#endif
To view particular message
<div class="col-sm-4">
<div class="form-group #if ($errors->has('post_name')) has-error #endif">
{!! Form::label('post_name','Post Name') !!}
{!! Form::text('post_name',old('post_name'),['placeholder'=>'Enter Post Name ','class' =>'form-control rounded','id' =>'post_name']) !!}
#if ($errors->has('post_name'))
<p class="help-block">{{ $errors->first('post_name') }}</p>
#endif
</div>
</div>
Hope it helps
I'm trying to import my excel to my database but the problem is that theres an error saying "Undefined index: title" referring to the title in the controller.
So this is my code for my controller
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader){
})->get();
if(!empty($insert)){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
print_r('Insert Record succesfully');
}
}
}
return back();
}
And this is for my view blade:
#extends('layouts.app')
#section('content')
<div class="container">
<button class="btn btn-success">Download Excel xls</button>
<button class="btn btn-success">Download Excel xlsx</button>
<button class="btn btn-success">Download CSV</button>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="import_file" />
<button class="btn btn-primary">Import File</button>
</form>
</div>
#endsection
Here is the image of the excel i want to upload to my database. It's an xlsx that i want to upload.
See picture for reference
But the error says like this Error message screenshot
You can insert the sheet data directly by calling the toArray method of the Maatwebsite\Excel\Readers\LaravelExcelReader.
$loadedFile = Excel::load($path);
$inserts = $loadedFile->toArray();
if (!empty($insert)) {
DB::table('items')->insert($insert);
print_r('Inserted Record successfully');
}
However, going by your implementation it should be noted that when a callback is specified for the reader, $reader->all() or $reader->get() returns a Maatwebsite\Excel\Collections\RowCollection or Maatwebsite\Excel\Collections\SheetCollection depending on the amount of sheets the file has.
For your sample where there is a single sheet, you can rightly expect a Maatwebsite\Excel\Collections\RowCollection. Therefore you have
$inserts = [];
Excel::load($path, function($reader) use (&$inserts) {
foreach ($reader->get() as $row) {
$inserts[] = ['title' => $row->title, 'description' => $row->description];
}
});
if (!empty($inserts)) {
DB::table('items')->insert($inserts);
print_r('Inserted Record successfully');
}
I submit the form and have some validation mean email,require,unique email,
when validation have error message then laravel 5.2 return validation return array.
I guess you want to retain the submitted data on error.
Considering a sample
public function postJobs(Request $request) {
$input = $request->all();
$messages = [
'job_title.required' => trans('job.title_required'),
];
$validator = Validator::make($request->all(), [
'job_title' => 'required'
], $messages);
if ($validator->fails()) { // redirect if validation fails, note the ->withErrors($validator)
return redirect()
->route('your.route')
->withErrors($validator)
->withInput();
}
// Do other stuff if no error
}
And, in the view you can handle errors like this:
<div class="<?php if (count($errors) > 0) { echo 'alert alert-danger'; } ?>" >
<ul>
#if (count($errors) > 0)
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
#endif
</ul>
</div>
And if you want the input data, you need to redirect with ->withInput(); which can be fetch in view like:
Update
<input name= "job_title" value="{{ Request::old('job_title') }}" />
But, the best thing is to use laravel Form package so they all are handled automatically.
If you just need form data, you can use Request object:
public function store(Request $request)
{
$name = $request->input('firstName');
}
https://laravel.com/docs/5.1/requests#accessing-the-request
Alternatively, you could use $request->get('firstName');
Use old() to get previous value from input. Example:
<input name="firstName" value="{{old('firstName')}}">
See documentation here https://laravel.com/docs/5.1/requests#old-input
I'm trying to validate a form but it doesn't show validation errors and if field is empty, it saves. How to validate form?
My code is:
public function action_upload()
{
if($_POST) {
$name = array(
'name' => Arr::get($_POST, 'name')
);
$validate = Validation::factory($name)
->rule('name', 'not_empty');
try {
$save = Model_Offers::Save($this->user['user_id'], $name);
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
}
My view is:
<form id="myForm" action="<?php echo URL::base()?>user/upload" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="file">Name: </label>
<input type="text" name="name" id="name"><br>
</div>
</form>
You created the validation object, but you forgot to actually apply the rules you assigned. Simply do this by calling
$validate->check()
It'd be best to put this in an if-else statement
if($validate->check()){
//Save object
}
else{
//Get errors (use $validate->errors())
}
Hope that helps! :)