php - Get the ip address from the form

I have a form to add a comment, everything works fine, except for getting the ip who sent the comment

Here is my controller

public function sendComment(Request $request)
    {
        $articleComment = new ArticleComment;

        $articleComment->name = $request->get('name');
        $articleComment->email = $request->get('email');
        $articleComment->text = $request->get('text');
        $article = Article::find($request->get('article_id'));
        $articleComment->user_ip = $request->ip();
        $article->article_comments()->save($articleComment);

        return back();
    }

To get ip, I use $request->ip() but in the end this value comes to my field "user_ip": "::1"

Maybe this is because I am testing everything on a local server, or what is the problem?

Answer

Solution:

Your code is correct if you want to store the IP address from the Request object.

You are getting ::1 as this the IPv6 address for your local machine. The request is coming from your own computer to the laravel app on your own computer therefore the IP is reported a localhost.

If you were running the Laravel app from the internet and sending the request that way, your own public facing IP would be stored properly with your existing code. This could be stored in IPv4 or IPv6 format depending on what your internet service provider is using.

It is suggested that to support storing both IPv6 (new style) IP addresses and IPv4 (old style) your database field should have a length of 45 characters.

Answer

Solution:

first check your Illuminate\Http\request.php file in line 296(public function ip() it's most be just return $this->getClientIp(); anything else is false, if is trye and didnot work, you have tow other ways to get the request ip:

1:

public function index(Request $request){
        return $request->getClientIp();
    }

2:

public function index(Request $request){
        return $request->server->get('REMOTE_ADDR');
    }

Source