moses toh
moses toh

Reputation: 13192

How can I display required message in 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?

Upvotes: 0

Views: 243

Answers (2)

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6004

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

Upvotes: 0

Alfredo EM
Alfredo EM

Reputation: 2069

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

Upvotes: 1

Related Questions