stephenjason
stephenjason

Reputation: 81

laravel route to controller being called twice

I am still learning laravel and have created a project with v5.4.28 also tested with dev v5.5 both versions calls the controller twice thus inserting 2 records. This only happens if I use WAMP and visit http://localhost/laravel/public/test?test=123

if i use php artisan serve and visits this http://127.0.0.1:8000/test?test=123 it only inserts once

if i inspect using chrome and see my network tab, i see the page being called twice on wamp.

Is this normal?

edited my routes/web.php to

Route::get('/', function () {
return view('home');
});
Route::get('/test', 'testController@store');

and created a testController

class testController extends Controller
{
    public function store()
    {
        $test = new Test;
        $test ->user_id = request('test');
        $test ->save();

        //if i put a redirect here then it wont insert twice
    }
}

Upvotes: 4

Views: 3422

Answers (1)

Murwa
Murwa

Reputation: 2278

This could also happen if you have a middleware making a double call to next. For instance, say you have a parent middleware's handle function as:

public function handle($request, Closure $next, ...$guards){
    // Your logic here
    return $next($request);
}

Now, assume you have a child middleware as below:

public function handle($request, Closure $next, ...$guards){
    // Note this call to the parent's next
    $resp = parent::handler($request, $next, $guards);
    // Extra logic here
    // ... and now we make another call to next
    return $next($request);
}

To avoid this, ensure you have a single call to next in your middleware's handle function.

https://laracasts.com/discuss/channels/laravel/controller-methods-called-twice-causing-duplicate-database-entries

Upvotes: 9

Related Questions