The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::route('registration')->withErrors($validator);
}
else {
//Some code here...
return Redirect::route('registration')->withMessage('Test message!');
}
}
Template:
#extends('default.base')
#section('main')
#if(!empty($errors->all()))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}
#endforeach
</ul>
</div>
#endif
#if(isset($message))
{{ $message }}
#endif
#stop
That is because errors is a special case. When creating a view, Laravel check's if there is a session variable with the name errors. If so it will then pass the contents as $errors to the view.
Illuminate\View\ViewServiceProvider#registerSessionBinder
if ($me->sessionHasErrors($app))
{
$errors = $app['session.store']->get('errors');
$app['view']->share('errors', $errors);
}
This means you either use Session::has('message') and Session::get('message') in your view or you add a View Composer that does basically the same that Laravel does with errors:
View::composer('*', function($view){
if(Session::has('message')){
$view->with('message', Session::get('message'));
}
});
Related
I want to do a function that returns a view, but if the item you're looking for isn't found, just return a hidden message in the view object.
public function getBannerById(string $banner_id): View
$banner = Banner::find($banner_id);
if (!$banner) {
return view()->append('<!-- Banner not found! -->'); // this not work
}
// more code ....
return view('banner', ['banner' => $banner]);
}
You can use the laravel Session for this, if the items isn't found so return to your view with the session message and then in the view you verify if exists the session and display the message.
In controller:
if (!$banner) {
Session::flash('error', "Banner not found!");
return view('view.name'); //
}
In View
#if (session('error'))
<div class="alert alert-danger" role="alert">
{{ session('error') }}
</div>
#endif
You can simply return Banner not found OR attach if-else statements in your blade file as below:
Controller code:
<?php
public function getBannerById(string $banner_id): View
$banner = Banner::find($banner_id);
return view('banner', compact('banner'));
}
View blade file:
#if(!$banner)
<p> Banner not found!</p>
#else
// Your view you wish to display
#endif
Update:
You can also use findOrFail method to automatically send 404 response back to the client if the banner is not found.
$banner = Banner::findOrFail($banner_id);
Strange issue here! My return code within the controller is as follows:
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
And then I display the errors within blade:
#if ($errors->any())
<article class="message is-danger">
<div class="message-body">
<ul>
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
</article>
#endif
However this doesn't appear to be working at all, $errors is empty for some reason, however this works fine from another controller!
This is the method where this works, I have included the use classes.
namespace App\Http\Controllers;
use App\Pages;
use App\PlannerStatus;
use App\SubPages;
use App\VehicleMake;
use App\Website;
use App\WebsiteRedirects;
use Illuminate\Http\Request;
use Redirect;
class RedirectsController extends Controller
{
public function store(Request $request, Website $website)
{
$error = [ 'test' => 'test error' ];
if (!empty($error)) {
return back()->withErrors($error)->withInput();
}
return back();
}
}
And this is the controller where this does NOT work, as you can see they are the same, more or less!
namespace App\Http\Controllers;
use App\ResultsText;
use App\VehicleMake;
use App\VehicleModel;
use App\VehicleType;
use App\SearchPath;
use App\Website;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\MessageBag;
use Redirect;
class ResultsTextController extends Controller
{
public function update(Website $website, ResultsText $resultsText, Request $request)
{
$data = request()->except(['_token','id']);
$result = ResultsText::where('id', $resultsText->id)->update($data);
if (!$result) {
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
}
return Redirect::action('ResultsTextController#index', $website);
}
}
Also here are my Routes, just so you can see they are pretty much identical:
Route::prefix('/redirects')->group(function () {
Route::get('/', 'RedirectsController#index')->middleware('SettingStatus:redirect');
Route::patch('/update', 'RedirectsController#update');
});
Route::prefix('/results-text')->group(function () {
Route::post('{resultsText}/update', 'ResultsTextController#update');
});
Inside your blade try this
#if ($errors->any())
<article class="message is-danger">
<div class="message-body">
<ul>
#foreach ($errors as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</article>
#endif
It's easily overlooked in your question. The problem is not what it seems. You will probably find it funny why it doesn't work.
Replace
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
with
return redirect()->back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
Can someone explain me why sometimes I have to use $errors->all() and sometimes not?
Struggling to find a unique solution for array of error and object $errors.
// View 1
#if (count($errors) > 0)
#foreach($errors as $error)
{{ $error }}<br>
#endforeach
#endif
// View 2 that sometimes it crashes with:
// "Call to a member function all() on array"
#if (count($errors) > 0)
#foreach($errors->all() as $error)
{{ $error }}<br>
#endforeach
#endif
$errors->all() using if you validate data via Validator or in the Request class. See this part of the documentation. Laravel share $errors variable as MessageBag class.
$errors as array using if in the controller you return something like this:
return back()->withErrors([
'field1' => 'Error in the field 1'
]);
In this case Laravel share $errors variable as array
I don't really do laravel that much but I assume you can always do something like this:
#if (count($errors) > 0)
#if(is_array($errors))
#foreach($errors as $error)
// code
#endforeach
#elseif(is_object($errors))
#foreach($errors->all() as $error)
//code
#endforeach
#endif
#endif
I manually created a Validator, but i can't find a method to get the validated data.
For Request, validated data return from $request->validate([...])
For FormRequest, it's return from $formRequest->validated()
But with Validator, i don't see a method like those 2 above.
Assuming that you're using Validator facade:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), $rules, $messages, $attributes);
if ($validator->fails()) {
return $validator->errors();
}
//If validation passes, return valid fields
return $validator->valid();
https://laravel.com/api/5.5/Illuminate/Validation/Validator.html#method_valid
If you use the Validator facade with make it will return a validator instance. This validator instance has methods like validate(), fails() and so on. You can look those methods up in the validator class or in the laravel api-documentation.
Writing The Validation Logic
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
Displaying The Validation Errors
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
View code:
<input type="file" name="queryfile" id="queryfile" required>
Here I am trying to upload the file with .sql extension.
Controller code:
public function debinsert1(Request $request)
{
$validator = Validator::make(Input::all(),
array(
'devicemodel' => 'exists:addProduct,productId',
'debfile' => 'mimes:deb',
'basefile' => 'mimes:deb',
'versions' => 'unique:MainHaghway',
**'queryfile' => 'mimes:sql',**
));
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
else{
$temp = new debModel;
if(Input::hasFile('queryfile')){
$file=$request->file('queryfile');
$file->move(public_path().'/downloads',$file-
>getClientOriginalName());
$temp->queryfile=$file->getClientOriginalName();
}
$temp->save();
In this controller code, I am trying to validate with the sql extension and if it succeeds need to insert into db. Validations for other files were working here but, .sql file is not passing with the validation.
Same view code(ie.,mentioned above):
#if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Here ,I am throwing the errors incase of failing validations.
This will not validate the sql file as laravel MIME type check here but .sql file don't have MIME type that why its not working but you can do this with manual check by use of php function pathinfo().
Just like this
if(pathinfo($request->queryfile->getClientOriginalName(), PATHINFO_EXTENSION)!=='sql'){
echo 'invalid sql file';
}
I thing it will help you.