1

Hello stackoverflow geeks, I'm in my final stages of the laravel learning curve all thanks to you guys. However, i need to generate a warning message like "You cannot delete a role assigned to a user" every time a user tries to delete a role assigned to a user. instead it loads a page with an sql error. how to i do it? And how do i avoid a password that has been already been stored from being hashed again. eg:- $2y$10$p8JwI5P4yE2UFo2.vHP99.0dP2jU7ll/9w73IzUa9/yegKOSTHJWq is always hashed every time i edit a user's information. Thanks you all who've made learning laravel easy for me by answering in time

code

 public function destroy(Request $request,$id) { // delete // $role = Role::find($id); //$role->delete(); $role = Role::find ($id); if ($role->users() !=null) { return redirect()->back()->withInput(['warning' => 'Not allowed']); } $role->delete(); // redirect Session::flash('message', 'Record successfully deleted!'); Session::flash('alert-type', 'success'); return Redirect::to('role'); } 

1 Answer 1

2

This highly depends on how you want to handle the errors. You can either catch the sql exception and display your custom error OR what is probably better for you is to handle the incoming request, validate it and return an error if validation fails.

Here are the validation docs : https://laravel.com/docs/5.3/validation

You have multiple options on how to validate a request. Simple example to validate a title is unique in the table posts and is maximum 255 chars long:

$this->validate($request, [ 'title' => 'required|unique:posts|max:255' ]); 

If you cannot find a rule that is helping you simply define your own validation rule https://laravel.com/docs/5.3/validation#custom-validation-rules

Ofcourse you can also do the validation manually. In your request or in your controller (depends on your setup) just check for it

// assuming you want to delete an entry public function delete(Request $request, $id) { $role = App\Role::findOrFail($id); if ($role->users() != null) { return redirect()->back()->withInput(['message' => 'Not allowed']); // now you can output $message } $role->delete(); return ... } 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Frank, validating manually has worked for me. It brings no error but it can't delete roles not assigned either and no error message is displayed
Try ->withInput(['warning' => 'Not allowed']); and in your template just output {{ $warning }}
i've included it above.
can you please also provide your blade template. Otherwise you could simply use Session::flash('message', 'Record cannot be deleted!'); before the redirect back

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.