VueJS: how to get route url? - laravel

I am working in laravel with Vue, and I can't get route url.
For example there is route localhost:8000/chat/3 and I need to get 3 in route
I tried in app.js to write in
data: {
userId: this.$route.params
}
and then in
created() {
console.log(this.userId);
}
So i can send ajax request to that route. But it returns TypeError: this.$route is undefined. I tried also with other things than params but it allways show this error

Related

Send POST request to Laravel web.php route

I have a simple Vue app in which I am sending POST request with options (table filtering variables) to the back-end. I want to be able to destructure the object and debug it in my TestController in Laravel 8, so I want to send the options to web.php via URL, not to api.php. Since options is an object, I cannot just drop it in the URL.
Ultimately I want to be able to preview my Laravel respond in browser, so I know it returns correct data from server.
So how can I achieve this?
in Vue FormComponent <form #submit="formSubmit"> and script
function formSubmit(e) {
e.preventDefault();
let currentObj = this;
axios.post('/formSubmit', {
name: this.name,
description: this.description
}).then(function(response) {
currentObj.output = response.data;
console.log(currentObj);
}).catch(function(error) {
currentObj.output = error;
});
}
Firstable, create POST route for your request. Then just make POST request to this route url and put your POST params (your object) to request body. You can use Axios as example
let filterOptions = {...};
axios.post(url, filterOptions).then().catch();
UPD And response for your request you can see in browser developer console on network tab

CSRF token mismatch From separate vue project to laravel controller

I have two projects running
One is front end
Other is backend
Frontend project is made in vue js and backend is made in laravel
I am trying to do a post request via axios but i get csrf token mismatch
I cant use the meta tag solution as they both are different projects
**Route i want to hit**
Route::group(['middleware' => 'auth'], function () {
Route::post('tasks', 'TaskController#store')->name('tasks.store');
});
**my axios call in my vue js project**
addTask:function()
{
this.displayError = false;
if($('.inputs').length > 0)
{
const config ={
onUploadProgress:function(progressEvent)
{
var percentCompleted = Math.round((progressEvent.loaded * 100)/progressEvent.total);
console.log(percentCompleted)
}
}
var form = new FormData();
form.append("title",this.title);
form.append("description",this.txtdesc);
form.append("status_id",this.status_id);
form.append("user_id",this.user_id);
axios.post("http://127.0.0.1:8020/tasks",form,config).then((res)=>{
console.log(res)
})
}else
{
this.displayError = true;
}
}
When i fire this function to send data to controller it gives csrf token mismatch error
If it was a laravel project i could've ha tried
adding {{csrf_field()}}
adding #csrf
adding csrf in meta
but how to do it in vue js
PS I have tried removing auth middleware but it returned the same error and
it will work if i place the route inside the cerifycsrftoken file in backend project
but i want to do it with csrf token
I placed my routes from web.php to api.php and added the prefix api which solved my csrf token mismatch problem
also if i place route url in verifyCsrfToken.php file it solves the issue without moving routes to api.php
I took route
Route::post('tasks', 'TaskController#store')->name('tasks.store');
from the web .php file and then i placed it in api.php file
Route::post('tasks', 'TaskController#store')->name('tasks.store');
also i didnt used auth middleware on them

Laravel: Redirect the user to a custom 404 page when the given params are invalid

I made an application where a user can create some papers and see all data in a template. Every paper has a joincode which is generated at its creation.
I defined the join route in my web.php like this:
Route::get('/conceptPaper/lobby/{joincode}', 'App\Http\Controllers\ConceptPaperController#join');
and the join function in the controller the following way:
public function join($joincode)
{
try {
$conceptPaper = ConceptPaper::where('join_code', $joincode)->firstOrFail();
return response()->json($conceptPaper);
} catch(ModelNotFoundException $e)
{
return view('errors.404');
}
}
I used firstOrFail to check if the join code exists. If it exists it should return a response, otherwise it should redirect the user to a custom 404 page.
I created a custom component which gets the join code as a route param and shows the concept paper
{
path: '/conceptPaper/lobby/:joincode',
name: 'conceptPaper',
component: () => import('./views/ConceptPaper.vue')
},
So when the user joins a lobby with the right code he gets redirected to the page with all data from the corresponding paper:
showPaper: async function (conceptPaper) {
const joinCode = conceptPaper.join_code;
this.$router.push({ name: "conceptPaper", params: { joincode: joinCode }, });
},
My problem is that when the user types in the wrong code he still gets redirected to the view. When I check the response in the network tab its shows the 404 page.
I think I built it fundamentally wrong. Can anyone tell me how to do it the right way? When the suer types in the correct join code he should see the ConceptPaper.vue view. When the code is wrong he should be redirected to the 404 page.
From your code I'm assuming that you're using VueJs as an SPA and you're retrieving the data from your laravel backend API.
Based on that, your join function is supposed to return json data that you use in your frontend, but in case the ConceptPaper was not found, you return a view instead of json, which won't change much because you're just changing the data that your front-end receives, but the front-end component is not changed.
What I'd do is remove the try catch block, which will return a 404 response from the API, and handle the 404 case in vue, and create a NotFound view in vue.
Laravel
public function join($joincode)
{
$conceptPaper = ConceptPaper::where('join_code', $joincode)->firstOrFail();
return response()->json($conceptPaper);
}
Vue
router/index.js
const routes = [
// previous routes
{
path: '/not-found',
name: 'NotFound',
component: () => import('../views/NotFound.vue')
}
]
NotFound.vue
<template>
// page here
</template>
export {
name: 'NotFound'
}
And finally handle the not found API call, if you are using axios
axios.get('/conceptPaper/lobby/-1000')
.catch(function (error) {
if (error.response.status === 404) {
this.$router.push('NotFound');
}
});

Axios is repeating prefix route in Laravel

I don't know why when I try to make a petition, axios didn't get the route well.
The error:
Then here's the error, I have a operations.js where I make an axios post to the route operation_calls as you see below, but I don't know why axios isn't getting only the url I wrote, it is getting repeating twice.
const operacionLlamadasApp = new Vue({
el: '.crud-operation-calls',
methods:{
storeOperations(){
// as you see I only write it once and I expect to go there
axios.post('operation_calls', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
}
}
});
When in the browser I'm in this url, creating a new row: http://my-domain/operation_calls/create and click on the save button I expect to go to operation_calls store route but I get this error:
Request URL: http://my-domain/operation_calls/operation_calls
Request Method: POST
Status Code: 405 Method Not Allowed
As you see, the prefix is repeated when I only typed it once.
Also I have this error in the response apart of my browser console:
The POST method is not supported for this route. Supported methods: PUT
I'm using:
Laravel 6.*
Axios: ^0.19
I've created routes like this:
Route::group(['prefix' => 'operation_calls'], function(){
Route::put('/{id}','OperationsCallController#update');
Route::resource('/','OperationsCallController', ['names' => [
'create' => 'operations.create']
]);
});
Basically, I have this routes:
GET|HEAD operation_calls index
POST operation_calls store
GET|HEAD operation_calls/create create
PUT operation_calls/{id} update
Here's the way I make the post method, in my blade.php I have this form:
<div class="crud-operation-calls">
<form role="form" method="POST" v-on:submit.prevent="storeOperations()">
#csrf
...
</form>
</div>
Also, I made a axios post only like this:
axios.post('', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
And this is what I get:
Request URL: http://my-domain/operation_calls/create
Request Method: POST
Status Code: 405 Method Not Allowed
I don't know what I'm doing wrong. It's like is passing the prefix of the current page. But I think axios just should go to the route I write in it's parameter. Why is it changing?
What I tried:
Clearing route cache of laravel: php artisan route:cache
Clearing cache of the browser
My .env file it's fine APP_URL=http://my-domain/ because it works with other urls.
Simply prefix your route with a / like this
axios.post('/operation_calls', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
I think you are directly posting from http://my-domain/operation_calls/create. So it assumes as relative URL appends extra URI there. Try
axios.post('{{ route('operation_calls.store') }}', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
Also, remove that <form> because we are posting via VUE, no need of extra FORM for posting. Use can change to <form> to <div>. Don't forget to pass CSRF token too in Vue post()

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

Resources