简体   繁体   中英

Laravel routing not working on MAMP

I've just started learning laravel and I'm using MAMP. I have a form at this url: http://localhost:8888/laravel-site/my-new-app/public/ducks but when I submit the form it takes me to this url: http://localhost:8888/ducks and doesn't stay where I'd expect it to.

The routes.php file contains this:

Route::get('ducks', function() 
{
    return View::make('duck-form');
});

// route to process the ducks form
Route::post('ducks', function()
{

    // process the form here

});

In my .htaccess file I have this:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteBase /laravel-site/my-new-app/public/

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I'm probably missing something really obvious, but why when I submit the form does it not stay on the same page?

Check to see if your app url set correctly in config/app.php:

'url' => 'http://localhost:8888/laravel-site/my-new-app/public',

And make sure your form is submitting to the correct route.

Form::open(array('route' => 'ducks'))

You haven't provided your form's HTML but my guess is that you hardcode something like the following and expect Laravel to make it work:

<form method="post" action="/ducks">

However, Laravel doesn't mess with your HTML. Instead you need to use the form helper to create your form for you. Try this:

{{ Form::open(['url' => 'ducks']) }}

That should make the correct URL for you. Remember not to use the / at the beginning of the URL, Laravel already assumes all URLs will be relative to the application root (though not necessarily web server document root).

Additionally to this, you should take other advice mentioned here:

  • Set your application's URL to http://localhost:8888/laravel-site/my-new-app/public in app/config/local/app.php
  • Use named routes to save hardcoding URLs all over your HTML

Simply use named route. It should help.

Route::get('ducks', array('as' => 'showForm', function() 
{
  return View::make('duck-form');
}));

// route to process the ducks form
Route::post('ducks', function()
{

// the get route is named as showForm
  return Redirect::route('showForm');
});

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