简体   繁体   中英

Can I display a message from return ->with() in laravel?

For example, I have a function and can I somehow display this message that the body should not be empty, display it on the screen?

public function store(Request $request){
        $comment = new Comment;
        $comment->body = $request->get('comment_body');
        if(empty($comment->body)){
            return back()->with('Body should not be empty! ');
        }else{
            $comment->user()->associate($request->user());
            $post = Article::find($request->get('article_id'));
            $post->comment()->save($comment); 
            return back();
        }

    }

You can redirect using flashed data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

So your controller should look like this:

        if(empty($comment->body)){
            return back()->with('error', 'Body should not be empty! ');

And in your view you can display the error like this:

@if (session('error'))
    <div class="alert alert-success">
        {{ session('error') }}
    </div>
@endif

But i strongly recommend you to read the validation section of the laravel documentation. You can achieve better results if you create a request or use the validate method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM