flex
flex

Reputation: 115

how to validate (check) data table values befour data insert in Laravel 5.2

I need validate and generate error message if same user try to insert existing project_name to the table in Laravel 5.2. My project table like this

user_id    project_name
    1          abc
    2          sdf
    3          kju

My project data store controller as follow

 public function store(Request $request)
    {
        $this->validate($request, [
            'name'     => 'required|min:3'

        ]);

        $project = new Project;
        $project->project_name   = $request->input('name');
        $project->user_id        = Auth::user()->id;

        $project->save();

        return redirect()->route('projects.index')->with('info','Your Project has been created successfully');
    }

and I have alert.blade.php file as

@if ( session()->has('info'))
    <div class="alert alert-info" role-"alert">
        {{ session()->get('info') }}
    </div>
@endif

@if ( session()->has('warning'))
    <div class="alert alert-danger" role-"alert">
        {{ session()->get('warning') }}
    </div>
@endif

how can I do this?

Upvotes: 0

Views: 540

Answers (2)

Tengda Su
Tengda Su

Reputation: 153

You could foreach the variable $errors if you want catch the error message, or if you are asking the validation rule, you could use 'exists:database'

https://laravel.com/docs/5.2/validation#rule-exists

Upvotes: 0

Shobi
Shobi

Reputation: 11461

If your form validation is failed then a 422(Unprocessable) response is returned by laravel. And an $error variable will be available in the response. So you can check if the variable is empty or not, and you can display the errors.

Like Below code. This is from laravel 5.2 documentation.

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

https://laravel.com/docs/5.2/validation

Upvotes: 1

Related Questions