How can I display required message in laravel? - laravel

My view like this :
{!! Form::open(['url' => 'product/store','class'=>'form-horizontal') !!}
...
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
{!! Form::textarea('description', null, ['class' => 'form-control', 'rows'=>5]) !!}
</div>
</div>
...
{!! Form::close() !!}
My controller like this :
use App\Http\Requests\CreateProductRequest;
public function store(CreateProductRequest $request)
{
dd($request->all());
}
My required like this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateProductRequest extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
return [
'description'=>'required'
];
}
}
If the description is not filled and click submit button, it will not be saved and it will return to the form. When returning to the form, I want to display a message that the description should be filled
I created an html to display a message like this :
<div class="alert alert alert-danger" role="alert">
Description is required
</div>
How can I call the html tag if the description is not filled?

For display a single message I usually use:
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif
for more information please check https://laravel.com/docs/5.4/validation#quick-displaying-the-validation-errors

Your all the validation errors are stored in $errors variable. You can access them using $error varibable. But must check if the error message exist using has() method as
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif

Related

How in laravel-livewire set flash message with validation erros

With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form

Array to string conversion using laravel

I am trying to send a multi user-id into the database when I select users from the checkbox then I click to submit so I face error Array to string conversion how can I resolve this issue? please help me thanks.
please see error
https://flareapp.io/share/17DKWRPv
controller
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
$user->save();
}
html view
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Users Permission </h3>
</div>
<br>
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<select name="userid" class="form-control">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<div class="card-body">
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" name="multiusersid[]" value="{{$user->id}}" class="form-check-input" >
<h5 style="position:relative;left:10px;">{{$user->name}}</h5>
</div>
<!-- checkbox -->
</div>
#endforeach
</div>
<!-- /.card-body -->
</div>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-md-2
center">Submit</button>
</div>
</form>
</div>
<!-- /.content-wrapper -->
Route
Route::post('adduseraction','AdminController#adduseraction')->name('adduseraction');
** current status **
{"_token":"4Z3ISznqKFXTMcpBKK5tUgemteqxuJjQpKF8F0Ma","userid":"6","multiusersid":["2","5","7"],"btnsubmit":null}
use implode($checkid, ',');
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> implode($checkid, ',');
]);
}
Change in your Users_permissions model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users_permissions extends Model
{
protected $table = 'userspermissions';
protected $fillable = [
'user_id','user_Access_id'
];
}
Here is your solution
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=implode(",", $request->get('multiusersid'));
Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
}
It is expecting a string and you are passing an array of ids. You may want to change the database to json or do json_ecode(checkid). Which will stringify your array. then you can store. However, remember you will need to convert it back with typecasting or manually doing it.
example:
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> json_encode($checkid)
]);
// $user->save(); // yes obviously not needed
}

How to fix this error in Laravel when creating a category

I am creating a website for a blog. I have added a category page quickly updated, but not returned to the index: category.php,CategoriesController.php. I'm using Laravel v5.5 and OpenServer.
Category.php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['title', 'slug',];
public function user()
{
return $this->belongsToMany(
User::class,
'id_idcat',
'gid',
'idcat'
);
}
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
CategoriesController.php
namespace App\Http\Controllers\Admin;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use View;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('admin.categories.index', ['categories' => $categories]);
}
public function create()
{
return view('admin.categories.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required' //обязательно
]);
Category::create($request->all());
return redirect()->route('admin.categories.index');
}
}
create.blade.php
{!! Form::open(['route' => 'categories.store']) !!}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" name="cat">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}
I can not find a mistake. I did similar tasks several times.
Your Data isn't validating as there is no input named title because it's named cat, so your validator is redirecting you back with errors, but your blade isn't showing errors so you don't see them.
Change Name of the field in your create view and add errors as below:
Edit: also add CSRF to form
create.blade.php
#if ($errors->any())
<div class="alert alert-danger" role="alert">
#foreach ($errors->all() as $input_error)
{{ $input_error }}
#endforeach
</div>
#endif
{!! Form::open(['route' => 'categories.store']) !!}
{{ csrf_field() }}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" placeholder="" name="title">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}

MethodNotAllowed Exception on form submit

routes.php
use App\Http\Controllers\Task;
use Illuminate\Http\Request;
Route::get('/', function () {
$tasks = Task::orderBy('created_at', 'asc')->get();
return view('tasks', [
'tasks' => $tasks
]);
});
Route::get('Login', 'Login#index');
View: loginform.blade.php
<form method="post" action="http://localhost/blog/public/Login">
<!-- Task Name -->
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
{!! Form::label('usernamelabel','Username', ['class'=>'col-sm-3 control-label']) !!}
{!! Form::text('username', '', ['class'=>'form-control','id'=>'username']) !!}
</div>
<div class="col-sm-6">
{!! Form::label('passwordlabel', 'Password', ['class'=>'form-control control-label']) !!}
{!! Form::text('password', '', ['class'=>'form-control','id'=>'password']) !!}
</div>
</div>
<!-- Add Task Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Login
</button>
</div>
</div>
{!! Form::close() !!}
Controller: Login.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Models\userloginModel;
use Illuminate\Http\Request;
class Login extends Controller{
protected $request;
public function index(Request $request)
{
echo view('login.loginform');
$foo = new userloginModel();
echo $foo->username = $request->username;
echo $foo->password = $request->password;
}
}
I have try all solutions from Stackoverflow and laracast but i failed to solve this please some one help me from this i am new with laravel..
Your error is in method, u trying to make a post request and your route are receiving a get request, try this:
Route
<?php
//...
Route::get('Login', 'Login#index');
Route::post('Login', 'Login#login');
?>
Controller
<?php
//...
public function index()
{
return view('login.loginform');
}
public function login(Request $request)
{
$foo = new userloginModel();
echo $foo->username = $request->username;
echo $foo->password = $request->password;
}
?>

Laravel - If has errors on validation, insert class in the specifics inputs

I'm totally noob in PHP, but my question is, after the validation which has errors for specific inputs, how can I insert a class in the specific input?
Example, if i have this error in the validation: "The email field is required."
How can i insert a specific class in the email input?
Login routes:
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'Admin\AdminController#index');
Route::get('login', 'Admin\AuthController#getLogin');
Route::post('login', 'Admin\AuthController#postLogin');
Route::get('logout', 'Admin\AuthController#getLogout');
});
AdminController:
class AdminController extends AdminBaseController
{
public function index()
{
if(Auth::user()){
return view('admin/pages/admin/index');
}
return view('admin/pages/login/index');
}
}
AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/admin';
public $loginPath = '/admin';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
public function getLogin()
{
if(Auth::user()){
return redirect('/admin');
}
return view('admin/pages/login/index');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
}
}
My blade form:
<form class="s-form" role="form" method="POST" action="/admin/login">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="s-form-item text">
<input type="text" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
<div class="s-form-item text">
<input type="password" name="password" value="{{ old('password') }}" placeholder="Senha">
</div>
<div class="s-form-item">
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
<input class="s-btn" type="submit" value="Entrar">
</div>
</form>
You can pass an argument to the has method to specify the specific key.
For example, for your email input...
<input class="#if($errors->has('email')) some-class #endif" ... >
I left out the rest of the input field for brevity. It basically checks if an error for the email input exists. If so, 'some-class' is outputted. Otherwise, it skips over it.
Edit: To answer the question on how you can customize where to output your error messages, you can use the get or first methods in conjunction with the has method. For example...
#if ($errors->has('email'))
#foreach ($errors->get('email') as $error)
<p>{{ $error }}</p>
#endforeach
#endif
The has method has already been explained. The get method retrieves the validation errors. Because there can be more than one validation error, you must loop through it and output it.
In the next example, I use first. This method just outputs the first error message so there is no need to loop through it.
#if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
#endif

Resources