Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jimb814's avatar

How to query the database when user logs in

I am new to Laravel. I have two types of users. I have a messages table that I want to query for unread messages when the user logs in.

I like the login functionality Laravel provides out-of-the-box, but I do not know where to put a query, or if this is even a good idea because there are better ways to handle it.

If anyone can help point me in the right direction, I would appreciate it.

0 likes
8 replies
jlrdw's avatar

You can do this query on the area the logged in user is redirected to after login.

Just have it first in the method, and notify user if unread messages, give user choice to read now or later,

jimb814's avatar

@jlrdw Thanks for the super speedy reply! The RouteServiceProvider redirects to /, and web.php assigns the HomeController to that route. Does that mean that I do this in HomeController@index?

siangboon's avatar

you may try setup the one-to-many relationship for your user and messages, and create a method in user model to retrieve unread flag messages and called at the controller..

take some times to watch Laracasts series, most of the lessons are related to Thread and Posts which quite similar to your case...

Snapey's avatar

Yes, consider that you might have a messages indicator in the header of the site. That indicator needs to be checked on every request to see if the user has unread messages (not just at login).

This is a perfect use for a view composer as long as you target just the view that contains the counter.

I would not change anything at login.

jimb814's avatar

@snapey Thanks for your input. I have an alarm bell icon to display if unread messages exist. This community of support is great!

Please or to participate in this conversation.