I created a component in vue file and I want to fetch data from laravel controller function.
Currently, I have used axios to fetch data. But can I directly call laravel controller function?
Thanks in advance.
-
You are doing right. Calling directly the controller from blade or vue is not a good practice.– Apurv BhavsarCommented Sep 8, 2021 at 6:16
-
Please provide enough code so others can better understand or reproduce the problem.– Community BotCommented Sep 13, 2021 at 9:05
4 Answers
No, the only way to communicate with your laravel app is your web service. ( Ex: REST Api )
Because Laravel and Vuejs are completely separated. Although in using web services you would have different methods.
- Expose a route from Laravel/Lumen app
- Call the route or url from vue using any http client(axios)
N.B: You cann't call the controller method on Laravel app directly from your Vue CLI
You need to do few steps.
in vue js file script area
const url = `https://www.naveedramzan.com/api/getData/users/4`;
Axios.defaults.headers.common['Authorization'] = `Bearer ${params.token}`; // if you are using some token authentication
Axios.get(url,{params: params})
.then((response) => {
res(response.data);
})
.catch((err) => {
rej(err);
});
In laravel, routes/api.php file
Route::post('getData/users', 'UsersController@getData');
In laravel, the controller file
use Illuminate\Http\Request;
public function getData(Request $request){
....
}
use this pacakge
composer require yudhees/laravel-vue-controller
By Installing this pacakge You can access your laravel controller within your vue file without writing any seperate api , By using this package You need to send your controller path and function name and also if the functions needs any params you can send this also .
for More detailed Information Vist here