Laravel CSRF Field in Vue Component - laravel

I would like to ask how can I add the csrf_field() in my vue component. The error is
Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
Here's the code:
<script>
export default {
name: 'create',
data: function(){
return {
msg: ''
}
},
props:['test']
}
</script>
<template>
<div id="app">
<form action="#" method="POST">
{{csrfToken()}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" id="location" class="form-control">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" id="age" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
</form>
</div>
</template>

As I already wrote here, I would simply suggest to put this in your PHP file:
<script>
window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>
This way you're able to easily import your csrfToken from the JS part (Vue in this case).
Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.
Source: I got the trick from this post.

Laravel version 5 or later
First you need to store your CSRF token in a HTML meta tag in your header:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then you can add it to your script:
<script>
export default {
name: 'create',
data: function(){
return {
msg: '',
csrf: document.head.querySelector('meta[name="csrf-token"]').content
}
},
props:['test']
}
</script>
And in the template:
<template>
<div id="app">
<form action="#" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" id="location" class="form-control">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" id="age" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<input type="hidden" name="_token" :value="csrf">
</form>
</div>
</template>

Try this:
<script>
export default {
name: 'create',
data: function(){
return {
msg: '',
csrf: window.Laravel.csrfToken
}
},
props:['test']
}
</script>
And in your markup just use
<input type="hidden" name="_token" :value="csrf" />
EDIT
Bit of a rabbit hole but, one great feature of Vue is that it can easily handle POST, PATCH, etc. requests using AJAX and the vue-resource extension. Instead of using a <form> here you can process this data using your Vue component. If you were to take this route, you can set default headers to send with each request no matter what method it is, so you can always send your CSRF token.
exports deafult{
http: {
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
}
}

if you look at the /resources/assets/js/bootstrap.js you will find these lines
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
I believe you are using axios for your requests. this means you need to add
<meta name="csrf-token" content="{{csrf_token}}">
in your <head> tag.

Came across this problem whilst building multiple forms in a vue v-for loop.
added to data;
csrf: document.head.querySelector('meta[name="csrf-token"]').content,
Added hidden form element
<input type="hidden" name="_token" :value="csrf" />

I think you need to write it like this:
{{ crsf_token() }}
and not like this:
{{ csrfToken() }}
If that doesn't work, maybe try this:
{!! csrf_token !!}

Related

Nuxt with Axios POST to Laravel's API

guys, :)
I'm no expert (yet) with API call's, am successful with Laravel on its own. So, need your help.
I am able to use Laravel + Nuxt in general. All connected POST and GET working fine on all CRUDs.
I've created a new department to this existing APP.
I am able to call GET and receive in return Data from API, no problem.
I am able to POST with Postman to API to this table/CRUD.
I'm unable to figure out how to POST with my form to API.
I know it's dead simple for some of you, but google this time couldn't answer straight away. Using VUE as an answer didn't help either. So, you're my only hope to be true.
Here is my code in Page file:
<template>
<section class="max-content page">
<TitleBox :title="'Dodaj Towar'" />
<DodajTowar button-text="Submit" submit-form="products" />
</section>
</template>
<script>
import TitleBox from '~/components/global/TitleBox.vue'
import DodajTowar from '~/components/magazyn/towar/DodajTowar.vue'
export default {
components: {
TitleBox,
DodajTowar
}
}
</script>
Here is the components file. They are connected and I can insert the data to DB only what I'll hardcode in this file:
<template>
<section class="container">
<div>
<form #submit.prevent="products">
<p>
<label for="name" class="input-label">Nazwa</label>
<input id="name" type="text" name="name" class="input">
</p>
<p>
<label for="description" class="input-label">Opis</label>
<input id="description" type="text" name="description" class="input">
</p>
<p>
<label for="price" class="input-label">Cena</label>
<input id="price" type="text" name="price" class="input">
</p>
<p>
<button type="submit" value="Submit" class="button btn-primary">
Zapisz
</button>
</p>
</form>
</div>
</section>
</template>
<script>
export default {
products() {
return {
name: '',
description: '',
price: ''
}
},
methods: {
products() {
// this.$axios.$post('api/warehouse/products', console.log(this.products))
this.$axios({
method: 'post',
url: 'api/warehouse/products',
data: {
name: 'Fred',
description: 'Flintstone',
price: '111'
}
})
}
}
}
</script>
Can you please provide me with an example of how should I do it the right way? The form is working fine on its own as well, in the dev tools in VUE, I can see what I'm typing and submit as products.
Sorry if this question was before, but I was unable to find the solution for the last days and run out of options.
You need to make your 'products' elements 'data' elements and bind your data elements to your form.
//change from 'products'
data() {
return {
name: '',
description: '',
price: ''
}
},
Then your form should look like this:
<form #submit.prevent="products">
<p>
<label for="name" class="input-label">Nazwa</label>
<input id="name" v-model="name" type="text" name="name" class="input">
</p>
<p>
<label for="description" class="input-label">Opis</label>
<input id="description" v-model="description" type="text" name="description" class="input">
</p>
<p>
<label for="price" class="input-label">Cena</label>
<input id="price" v-model="price" type="text" name="price" class="input">
</p>
<p>
<button type="submit" value="Submit" class="button btn-primary">
Zapisz
</button>
</p>
</form>
The v-model attribute will bind the data elements to the inputs.
When you access the data elements in your method, you need to use 'this'.
products() {
this.$axios({
method: 'post',
url: 'api/warehouse/products',
data: {
name: this.name,
description: this.description,
price: this.price
}
})
//add a .then() and a .catch() here to deal with response.
}
And that should do it.

Laravel Vuejs form builder

In my project i have some events, each with a number of tags.
These tags are defined by the administrator user.
Some of these tags may have parameters.
For example, an email tag has two "Sender" and "Receiver" parameters.
Or the transfer tag has 2 parameters "From" and "To". and etc.
Do I have to use the form builder?
How do I implement this using Laravel and Vuejs?
Use Vue JS Component in Laravel like this.
Create Contact.vue component inside resources\assets\js\components then place your Vuejs there.
<template>
<div>
<h1>Contacts</h1>
<form action="#" #submit.prevent="createContact()">
<div class="form-group">
<label>Name</label>
<input v-model="contact.name" type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input v-model="contact.email" type="text" name="email" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">New Contact</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function(){
return {
contact:{
name:'',
email:'',
}
}
},
methods: {
createContact: function(){
//call axios to submit the form values in your Laravel controller method
let self = this
axios.post('/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
})
.catch(function(error){
console.log(error);
});
console.log(this.contact);
return;
}
}
}
</script>
In app.js file inside \resources\assets\js add the component
Vue.component('contacts', require('./components/Contacts.vue'));
Finally, call the contacts component inside your blade file.
<div class="container">
<div id="app">
<contacts></contacts>
</div>
</div>

The POST method is not supported for this route. Supported methods: GET, HEAD

Iam trying to update a specific data using post method. After submitting the form it shows an error : The POST method is not supported for this route. Supported methods: GET, HEAD.
editpage.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<h3>Update Book</h3>
<br>
<form action="update" method="post" >
{{csrf_field()}}
#foreach($array as $fetch)
<div><input type="hidden" name="id" value="{{$fetch->id}}"></div>
<div><input type="text" name="name" class="form-control " placeholder="Bookname" value="{{$fetch->name}}" ></div><br>
<div><textarea name="content" class="form-control" rows="5" placeholder="Description" >{{$fetch->content}}</textarea></div><br>
<div><input type="text" name="author" class="form-control" placeholder="Author" value="{{$fetch->author}}"></div> <br>
<div><input type="submit" name="submit" value="Update Book" class="btn btn-success" ></div>
#endforeach
</form>
</div>
#endsection
Web Route
Route::get('/', function () {
return view('welcome');
});
Route::get('/addbook',function () {
return view('AddBook');
});
Route::post('/insert',['uses'=>'BookController#insert']);
Route::get('/delete/{id}',['uses'=>'BookController#delete']);
Route::get('/edit/{id}',['uses'=>'BookController#edit']);
``````
Route::post('/update',['uses'=>'BookController#update']);
```````
Route::get('/home',['uses'=>'BookController#index']);
Auth::routes();
There are action like update which requires the method submitted to the server url to be either PUT/PATCH (to modify the resource)
Try with this,
<form action="{{ route('book.update') }}" method="post" >
{{csrf_field()}}
{{ method_field('PUT') }}
#foreach($array as $fetch)
// ...
#endforeach
</form>
Your Route,
Route::put('update',['uses'=>'BookController#update', 'as' => 'book.update']);
Your Controller
public function update(Request $request)
{
// ...
}
Hope this helps :)

using route resource form did not post to store function

I have a form which upon successful validation should show the desired result. But on button press the browser displays The page has expired due to inactivity. Please refresh and try again.
view page
<form class="form-horizontal" method="POST" action="{{action('BookController#store')}}">
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" required="required" runat="server" id="txtBookName" class="form-control" autocomplete="off" autofocus="autofocus" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
Route code
//web.php
Route::resource('book','BookController');
controller code
class BookController extends Controller
{
public function index()
{
//
}
public function create()
{
return view('pages.book');
}
public function store(Request $request)
{
$validatedInput = $request -> validate([
'txtBookName' => 'required|string|min:3|max:100'
]);
return $validatedInput;
}
}
Form url
http://127.0.0.1:8000/book/create
on submit button press, the page is redirected to
http://127.0.0.1:8000/book and it displays The page has expired due to inactivity. Please refresh and try again.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php:
protected $except = [
'your/route'
];
Implement like this to avoid Expired message.
<form action="{{ action('ContactController#store') }}" method="POST">
#csrf <!-- this is the magic line, works on laravel 8 -->
<!--input components-->
<!--input components-->
<!--input components-->
</form>
you should use {{ csrf_field() }} in your form.
Please do this after the form class, because the resource take the #method('PUT')
<form class="form-horizontal" method="POST" action="{{action('BookController#store')}}">
{{csrf_field()}}
#method('PUT')
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" required="required" runat="server" id="txtBookName" class="form-control" autocomplete="off" autofocus="autofocus" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>

Naming convention of v-model for Vuejs and Axios in a POST request (Issues encoding a Vue Object into JSON)

this is going to be super long winded!
Admittedly I am not a good frontend designer and my Javascript skills leave much to be improved upon.
TL:DR - How is the working code different from the JSON encoded data object (merchant) in the non-working code, in regards to the Axios POST request? Shouldn't they produce the same result?
Some background first: I am building a Laravel REST backend that is feature complete, form validators, policies, the works. I have tested the backend with the ARC REST client for Chrome and have verified my backend is fully functional.
The problem: While designing my frontend using Vuejs, Vue-Router and Axios, I am having issues POSTing data to my backend. Specifically it is failing form validation with an HTTP error 422. I have narrowed down this issue to be relating to object encapsulation in either Vue or Axios.
Here is the non-working Vue component:
<div class="panel panel-default">
<div class="panel-heading">Create Merchant</div>
<div class="panel-body">
<form action="#" #submit.prevent="createMerchant()">
Primary
<input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
Alternate
<input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
Contact
<input v-model="merchant.contact" type="text" name="contact" class="form-control">
Street
<input v-model="merchant.street" type="text" name="street" class="form-control">
City
<input v-model="merchant.city" type="text" name="city" class="form-control">
State
<input v-model="merchant.state" type="text" name="state" class="form-control">
Country
<input v-model="merchant.country" type="text" name="country" class="form-control">
Postal Code
<input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
<button type="submit" class="btn btn-primary">Create Merchant</button>
</form>
</div>
</div>
<div v-if='errors && errors.length' class="panel panel-default">
<div class="panel-heading">Error</div>
<div class="panel-body">
<ul>
<li v-for='error of errors'>
{{error.message}}
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
merchant: {
primary: '',
alternate: '',
contact: '',
street: '',
city: '',
state: '',
country: '',
postalCode: ''
},
errors: []
};
},
methods: {
createMerchant() { console.log(JSON.stringify(this.merchant));
axios.post('/payment-gateway/public/api/v1/merchant', JSON.stringify(this.merchant))
.then((response) => {
console.log(response.data.id);
this.$router.push({ name: 'merchantList' });
})
.catch(e => {
this.errors.push(e);
});
}
}
}
</script>
The data being posted, from my point of view appears to be correct:
{"primary":"Widget Company","alternate":"Widget Co","contact":"555-555-0055","street":"123 Main St","city":"Olympia","state":"WA","country":"USA","postalCode":"98501"}
But the above code always results in a HTTP 422 error.
Now for the part that is confusing me, this is working code:
<div class="panel panel-default">
<div class="panel-heading">Create Merchant</div>
<div class="panel-body">
<form action="#" #submit.prevent="createMerchant()">
Primary
<input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
Alternate
<input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
Contact
<input v-model="merchant.contact" type="text" name="contact" class="form-control">
Street
<input v-model="merchant.street" type="text" name="street" class="form-control">
City
<input v-model="merchant.city" type="text" name="city" class="form-control">
State
<input v-model="merchant.state" type="text" name="state" class="form-control">
Country
<input v-model="merchant.country" type="text" name="country" class="form-control">
Postal Code
<input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
<button type="submit" class="btn btn-primary">Create Merchant</button>
</form>
</div>
</div>
<div v-if='errors && errors.length' class="panel panel-default">
<div class="panel-heading">Error</div>
<div class="panel-body">
<ul>
<li v-for='error of errors'>
{{error.message}}
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
merchant: {
primary: '',
alternate: '',
contact: '',
street: '',
city: '',
state: '',
country: '',
postalCode: ''
},
errors: []
};
},
methods: {
createMerchant() { console.log(JSON.stringify(this.merchant));
axios.post('/payment-gateway/public/api/v1/merchant', {
primary: this.merchant.primary,
alternate: this.merchant.alternate,
contact: this.merchant.contact,
street: this.merchant.street,
city: this.merchant.city,
state: this.merchant.state,
country: this.merchant.country,
postalCode: this.merchant.postalCode
})
.then((response) => {
console.log(response.data.id);
this.$router.push({ name: 'merchantList' });
})
.catch(e => {
this.errors.push(e);
});
}
}
}
</script>
So my question is, how is the working code different from the JSON encoded data object (merchant) in the non-working code?
In one instance you're sending an object, in the other a string. Although they will both be transferred as a string eventually, when you pass the object, the ContentType is set under the hood to application/json.
That being said, if you set the ContentType to application/json for the one you're passing as a string, it will sort the issue.

Resources