Correctly redirect to another page with inertia?

Nancy picture Nancy · Oct 22, 2019 · Viewed 8.2k times · Source

I"m trying to redirect on click to another page, for some reason it's not working. This is the code on my vue where the redirect buttons are. I've tried two different ways and neither are working.

<el-row class="import-btn">
    <a :href="'/imports/teachers'">
        <el-button type="warning">                                     Importar
        </el-button>
    </a>
</el-row>
<el-row class="import-btn">
    <el-button type="warning"                               
        @click="redirectStudents()">                                    Importar
    </el-button>
</el-row>
redirectStudents() {      
  this.$inertia.visit('/imports/students');
},

I have the web.php routes like this

Route::resource('imports/students', 'ImportStudentController');
Route::resource('imports/teachers', 'ImportTeacherController');

In both the controllers I currently just have the index() filled

public function index()
{
   return Inertia::render('Import/Students');
}
public function index()
{
    return Inertia::render('Import/Teachers');
}

In the vue files for Teachers and Students I have basic layout and titles for those pages, so they're not empty.

When I click on the <a :href=""> button I get redirected to the link but the page is totally blank and when I click on the other button it opens up like a window inside also blank.

What is the correct way to fix this?

Answer

Linus Juhlin picture Linus Juhlin · Nov 19, 2019

Links

Creating a link in InertiaJS is pretty straight-forward. It has a custom tag as to denote that it's something that falls into the domain of the framework.

<inertia-link href="/">Home</inertia-link>

Under the hood there is a <a> tag, which also means that all attributes passed will be sent to that underlying <a> tag.

Redirect

If all you're really looking for is a simple link-click - and not a redirect per se - then you're fine with the above code.

If you're instead interesting in a redirect - for example after updating a user or the something similar - then simply using the Redirect facade like you would do in any other Laravel application is sufficient.

class UsersController extends Controller
{
    public function store()
    {
        User::create(
            Request::validate([
                'name' => ['required', 'max:50'],
                'email' => ['required', 'max:50', 'email'],
            ])
        );

        return Redirect::route('users');
    }
}

If you've installed the InertiaJS laravel adapter package, then this redirect will return a 303 status code, which is the same as a 302 status code, except that the request is changed into a GET request.

Hope this helps!