Laravel + Vue : Routes on web.php / api.php

Published 1 week ago by Neewd

Hello guys,

I am quite a new guy on Laravel and I have started working on a project, and I would like get some advice about the good architecture to pick.

I decided to manage my front with Vue and my backend with Laravel.

What I have started to do is to capture the routes through Laravel and sent it to my Vue routes to determines which components to load etc. And I was thinking to make "api" calls though axios into my Vue.components to retrieve the data from my controller in order to display them into my view.

That's still a "web" logic.

But I am also thinking to the future API I will provide.

So what is the best option to take ?

Put some Route::resource('model', 'Controller') into the web.php file, then call those routes in my Vue.components, and put the Route::resource('model','Controller') into my api.php file ?

Thank you for your answer I don't know if I am going the right way or not.

Clément.

Sergiu17
Sergiu17
1 week ago (140,580 XP)

Hi, if your application is SPA ( single page application ) then your routes should be in api.php but if your application is combined between http and Ajax requests, then nothing is wrong to put your routes in web.php

Snapey
Snapey
1 week ago (898,995 XP)

Disagreeing with @Sergiu17

If you have an authenticated user, use the web routes so that you can use sessions

api is for calls by other servers or mobile devices running applications

Neewd

Hello,

Thanks you both for your answers. My need is to call my API in the front-end via Vue.js, if I put my ::resource routes on the api.php, and if I use the CreateFreshApiToken for my API auth, that fills my need no ? https://laravel.com/docs/5.6/passport#consuming-your-api-with-javascript

Snapey
Snapey
1 week ago (898,995 XP)

That will be ok but using sessions, there is no need to touch passport at all

Neewd

If I want to use the CreateFreshApiToken, it comes from Passport, how I can use this without Passport ? :o

I have another question about the consumption of my API through my javascript framework. I put my API routes in my 'api.php', and my web routes - and Auth::routes in my web.php. The CreateFreshApiToken middleware will be add to the web groups middleware, so when I'll make a login, the reply will contains a token, and when I will make an axios call to my API, I have to send the X-CSRF-TOKEN and the width in the headers, and all gonna be right, right ?

Snapey
Snapey
1 week ago (898,995 XP)

Go all-in with passport or don't touch it. There is no need for a hybrid.

If your user logs into your application and you serve them your SPA, all the axios requests made by the browser will submit the session cookie automatically. This is not the same as csrf.

Please sign in or create an account to participate in this conversation.