In the routes.php
Route::get('/form1', 'FriendsController#getAddFriend');
Route::post('/form1', 'FriendsController#postAddFriend');
In the app/Http/Controllers/FriendsController.php
namespace App\Http\Controllers;
use App\Http\Requests\FriendFormRequest;
use Illuminate\Routing\Controller;
use Response;
use View;
class FriendsController extends Controller
{
public function getAddFriend()
{
return view('friends.add');
}
public function postAddFriend(FriendFormRequest $request)
{
return Response::make('Friend added!');
}
}
In the app/Http/Requests/FriendFormRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class FriendFormRequest extends Request
{
public function rules()
{
return [
'first_name' => 'required',
'email_address' => 'required|email'
];
}
public function authorize()
{
return true;
}
public function forbiddenResponse()
{
return Response::make('Permission denied foo!', 403);
}
public function response()
{
}
}
In the resources/views/friends/add.blade.php
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
<form method="post">
<label>First name</label><input name="first_name"><br>
<label>Email address</label><input name="email_address"><br>
<input type="submit">
</form>
when i run by http://localhost/laravel/public/form1
I am getting error as "Whoops, looks like something went wrong."
When I remove the following line
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
It displays the form
What is the error?
What I can think of is that your $errors variable is not existing and that's what causes the script to throw an exception.
1. If you are using Laravel 5.2 you might find your answer here:
Undefined variable: errors in Laravel
Basically in in app/Http/Kernel.php you need to check if $middlewareGroups['web'] contains
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
2. If you are using another Laravel version, probably you can add an additional check like this:
#if(isset($errors))
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
#endif
To further investigate the problem you need to give us the stack trace of the exception. If you only see the "Whoops ..." message, then go in you .env file and change APP_DEBUG = true
Related
I'm using Laravel 5.7 and I am getting errors in this code.
CustomersController.php
<?php
use App\Customers;
use Illuminate\Http\Request;
class CustomersController extends Controller
{
public function list()
{
$customers = Customer::all();
return view('internals.costumers.blade.php',[
'customers' => $customers
]);
}
}
internals.costumers.blade.php
#extends('layout')
#section('content')
<h1>This is Customers</h1>
<ul>
#foreach ($customers as $customer)
<li>{{ $customer->name }}</li>
#endforeach
</ul>
#endsection
Please define namespace in controller and in view helper pass only name of blade file with parameters instead of with extension: .blade.php
This did not show the errors after submit
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
$this->validate($request,[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
Inserting values into the database.I want to validate on submitting the form
public function store(Request $request)
{
//
$this->validate($request->all(),[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
I displayed errors like this, but not working for me
#if(count($errors) > 0)
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
Add this piece of code on your controller method.
return back()->withErrors()->withInput()
you can also access old input value with old(field_name)
Use ->all() here to provide all input value in to validate
$this->validate($request->all(),[
Or you can try like this
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
And display error as
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
first, edit your method like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
use Validator;
and inside this method please edit your redirect route and make sure your redirect url, redirect you in the page that had the error message:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
if ($validator->fails()) {
return redirect(route('make your route here '))
->withErrors($validator)
->withInput();
}
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
and for displaying error messages inside your blade template make this :
#if(!empty($errors))
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
#endif
#endif
I created a validation but cant show it on view, its important to return search view and don't redirect back user. help me please, thanks all?
Controller :
public function search(Request $request)
{
$msg = Validator::make($request->all(), [
'search' => 'required'
]);
if ($msg->fails()) {
return view('layouts.search')->withErrors($msg->messages());
} else {
return "Thank you!";
}
}
View :
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error}} </li>
#endforeach
</ul>
#else
You can use $error->first('name_of_error_field') to show error messages.
You can do it like this:
public function search(Request $request)
{
$validator = Validator::make($request->all(), [
'search' => 'required'
]);
if ($validator->fails()) {
return view('layouts.search')->withErrors($validator); // <----- Send the validator here
} else {
return "Thank you!";
}
}
And in view:
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error->first('name_of_error_field')}} </li>
#endforeach
</ul>
#endif
See more about Laravel Custom Validators
Hope this helps
In the login system I'm creating in Laravel (Version 5.2), the registration request is passed on to the RegistrationRequest class, which contains the validation logic like this:
public function rules() {
return [
"username" => "required|min:3|unique:users",
"password" => "required|min:6|confirmed",
"email" => "required|confirmed|email|unique:users",
];
}
which is then passed on to the postRegistration function:
public function postRegistration(RegistrationRequest $request) {
$this->user->username = $request->input('username');
$this->user->mail = $request->input('email');
$this->user->password = password_hash($request->input('password'), PASSWORD_DEFAULT);
$this->user->save();
$this->auth->login($this->user);
return redirect('/dashboard');
}
All kind of basic stuff, now the problem that I have is that I have no idea how to show an error when my username is for example 2 characters long.
I know that normally, I'd do
return redirect('/registration)->withInput()->withErrors(["errorHere" => "value"]);
but since the validation rules are external, I have no clue how to pass those to a view.
I searched some forums and the docs, but I couldn't find anything clear on it.
Is there a way to show these errors, preferably with the withInput() method?
Thanks.
As you can see from the Docs from laravel:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
EDIT: Didn't notice the author itself answered the question until I refreshed the page.
So exactly one minute after asking this, a friend messaged me and told me that i could just do the following:
#if (count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{ { $error } }</li>
#endforeach
</ul>
#endif
Having a real confusing time with this project, my issue is I'm trying to get my search working but for some reason its not pulling results from my query when there is that information in the database, also when I click on the username in the top corner of my page, it should redirect to the user page but instead I get this error "NotFoundHttpException in Application.php line 879:" with the URl looking like this "http://localhost/WorldLink/users/firstName%20=%3E%20Auth::user%28%29-%3EfirstName" and I have exhausted all other means of trying to fix it so I'm back for some help! my code is below Im using laravel 5.2:
Users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
protected $table = 'users';
protected $fillable = [
'id', 'firstName', 'lastName', 'bio', 'homeLocation', 'currentLocation', 'email', 'password',
];
public function getName()
{
if ($this->firstName && $this->lastName) {
return "{$this->firstName} {$this->lastName}";
}
if ($this->firstName) {
return $this->firstName;
}
return null;
}
public function getNameOrLocation()
{
return $this->getName() ?: $this->currentLocation;
}
public function getFirstNameOrLocation()
{
return $this->firstName ?: $this->currentLocation;
}
public function getAllAvatarsUrl()
{
return "https://www.gravatar.com/avatar/{{ md5($this->email) }}?d=mm&s=40";
}
}
SearchController.php:
<?php
namespace App\Http\Controllers;
use DB;
use App\Users;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class SearchController extends BaseController
{
public function getResults(Request $request)
{
$query = $request->input('query');
if (!$query) {
return back();
}
$users = Users::where(DB::raw("CONCAT(firstName, ' ', lastName)"), '
LIKE', "%{$query}%")
->orWhere('currentLocation', 'LIKE', "%{$query}%")
->get();
return view('search/results')->with('users', $users);
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class ProfileController extends BaseController
{
public function getProfile($firstName)
{
$users = User::where('firstName', $firstName)->first();
if (!$users) {
abort(404);
}
return view('profile.index')
->with('users', $users);
}
}
userblock.blade.php
<div class="media">
<a class="pull-left" href="{{ route('profile/index', ['firstName' => $users->firstName]) }}">
<img class="media-object" alt="{{ $users-getNameOrLocation() }}" src="{{ $users->getAllAvatarsUrl() }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ $users->getNameOrLocation() }}</h4>
</div>
#if ($users->currentLocation)
<p>{{ $users->currentLocation }}</p>
#endif
results.blade.php
#extends('layouts.app')
#section('content')
<h3>Search Results for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No Results Found</p>
#else
<div class="row">
<div class="col-lg-12">
#foreach ($users as $user)
#include('users/partials/userblock')
#endforeach
</div>
</div>
#endif
#endsection
And finally my two routes, the problem is connected in here somewhere I just cant find where its going wrong.
Route::get('/search', [
'uses' => '\App\Http\Controllers\SearchController#getResults',
'as' => 'search/results',
]);
Route::get('/users/{firstName}', [
'uses' => '\App\Http\Controllers\ProfileController#getProfile',
'as' => 'profile/index',
]);
The Link:
#if (Auth::guest())
<li>Login</li>
<li>Register</li>
#else
<ul class="nav navbar-nav">
<form class="navbar-form navbar-left" role="search" action="{{ route('search/results') }}">
<input type="text" class="form-control" placeholder="Search" name="query">
</form>
<li>{{ Auth::user()->firstName }}</li>
<li>Timeline</li>
<li>Link</li>
<li>Journeys <span class="journey-num">{{ Auth::user()->journeys }}</span></li>
<li>Forum</li>
</ul>
Defo quoting incorrectly
....
<li>{{ Auth::user()->firstName }}</li>
....
Note closing ' moved to after firstName array key.
That should at least fix the link