Chris
Chris

Reputation: 949

redirect using button onclick

I am using the Laravel framework and the blade templating engine.

What I would like to do, is have 2 buttons in my view, when clicked will redirect you to another view. The code I tried was:

 <button type="button" onclick="{{ Redirect::to('users.index') }}">Button</button>

Upvotes: 10

Views: 85082

Answers (3)

The Alpha
The Alpha

Reputation: 146191

You may try this (assuming this code is in a blade template):

<button type="button" onclick="window.location='{{ url("users/index") }}'">Button</button>

However, {{ url('users/index') }} will print the URL so, it'll become something like this in the browser:

<button type="button" onclick="window.location='http://example.com/users/index'">Button</button>

It means that you have a route declared something like this:

Route::get('users/index', array('uses' => 'UserController@index', 'as' => 'users.index'));

In this case, may also use:

<button type="button" onclick="window.location='{{ route("users.index") }}'">Button</button>

The output will be the same.

Upvotes: 22

Dominique Theodore
Dominique Theodore

Reputation: 11

You can also style an href tag as a button. For example <a class="btn btn-primary" href="{{ route('users.create' }}">Create</a> This helps to avoid mixing javascript and blade directives.```

Upvotes: 1

msurguy
msurguy

Reputation: 524

Yeah, you would need to basically use the URL helper to generate the URL (same as just putting something like http://yoursite.com/users instead of the PHP helper):

<button type="button" onclick="window.location='{{ URL::route('users.index'); }}'">Button</button>

Although I don't see why you can't just use an "a href" tag instead of the button, like this:

<a href="{{ URL::route('users.index'); }}">My button</a>

Upvotes: 2

Related Questions