Passing data from Vue.js request to Laravel 5.3 form - laravel-5

I have two tables: Countries and Cities. Idea is to show the second dropdown when User has selected country and fill it with cities that correspond to selected country.
Unfortunately I cannot figure out how to pass retrieved values to form.
Values retrieved are below the country with id 21 is Norway :)
Selected { "country": "21", "CountrySelected": true, "cities": { "6": "Oslo", "11": "Lillehammer" } }
// My app.js
const app = new Vue({
el: '#events',
data: {
country:'',
CountrySelected: false,
cities:[],
},
methods: {
WhenCountryHasBeenSelected: function(event) {
this.getCities();
this.CountrySelected= true;
},
getCities: function(){
this.$http.get('api/cities/'+this.country).then(function (response) {
this.cities = response.data;
});
}
},
})
//My api.php routes
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$cities=App\City::where('country_id', $country_id)->get()->pluck('name','id');
return $cities;
});
//My blade file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div id="events">
<div class="panel panel-default">
<div class="panel-heading">Select cities by country</div>
<div class="panel-body">
{!! Form::open() !!}
{!! Form::select('country', $countries, null, ['v-model'=>'country', '#change'=>'WhenCountryHasBeenSelected' ,'class'=>'form-control']) !!}
<div v-show="CountrySelected">
{!! Form::select('city',$cities, null, ['class'=>'form-control']) !!}
{!! Form::close() !!}
Selected #{{ $data | json }}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection

Ended up to use Laravel collection map feature. Mu route looks now like this
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$collection=App\City::where('country_id', $country_id)->get();
$cities=$collection->map(function($city){
return ['id' => $city->id, 'name' => $city->name];
})->toArray();
Long live Laracast forums and bashy :)

Related

How to get proper data when using blade components and alpinejs?

I'm new in components and alpine in laravel. I have data from controller $positions.
$positions = [
['id' => 1, 'content' => 'king'],
['id' => 2, 'content' => 'lord']
];
When I pass it to laravel blade. here is my code
<div class="row">
<div class="col">
#foreach($list as $key => $position)
<x-list :position="$position"/>
#endforeach
</div>
</div>
I have component name it <x-list/> with a prop position, and here is the code of my x-list component
<div class="red w-60 mb-1">
<div x-data="positionData()" class="relative">
<button #click="submit()" class="p-2">Submit</button>
</div>
</div>
<script>;
var position = #json($position);
function positionData() {
return {
submit() {
console.log(position);
},
};
}
</script>
It is just very simple code but when I click the submit button, the data I get is the last position
from the list ['id' => 2, 'content' => 'lord'], even I click position 1 the data I get is still position 2 data. I don't know what happen now. I try to search it in google to fix it but I can't find the right answer on this.
I think the issue in this case is that the positionData function is being overwritten on each iteration of x-list (since each of the components is creating a new window.positionData function).
To solve it you could do:
<div class="red w-60 mb-1">
<div x-data="positionData(#json($position))" class="relative">
<button #click="submit()" class="p-2">Submit</button>
</div>
</div>
<script>;
function positionData(position) {
return {
submit() {
console.log(position);
},
};
}
</script>
Specifically, you should probably move the <script></script> out of the x-list component so that it doesn't get re-created for each component (it should only be added to the page once).

How to insert data with logged in user id? Laravel-6

I want to submit data to bidding table with logged in user id and auction id from product show method.
This is how my tables are in relation.
Is it good to use ProductController or should I create another controller for bidding table?
Product show blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="my-3 border">
<div class="row">
<div class="col-md-5">
<img src="/storage/images/{{$product->image}}" alt="" style="width: 100%;">
</div>
<div class="col-md-7">
<h2>{{$product->name}}</h2>
<p>{{$product->description}}</p>
<span>Category: {{$product->category->name}}</span><br>
<span class="text-right">Auction Ends: {{$product->auction->deadline}}</span>
<div class="price">Initial Price: {{$product->price}}</div>
{!! Form::open(['action' => 'BiddingsController#create', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-inline">
{{Form::number('bidamount', '',['class' => 'form-control mr-1', 'placeholder' => 'Place your bid'])}}
{{Form::submit('Place Bid', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
#endsection
Bidding controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Bidding;
class BiddingsController extends Controller
{
public function index()
{
$biddings = Bidding::all();
return view('products.show' ,compact('biddings', $biddings));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show(Bidding $bidding)
{
//
}
}
In a Laravel 6 app, you can get the Logged in user using the auth() helper.
$authUser = auth()->user();
Doc: https://laravel.com/docs/6.x/helpers#method-auth
Cordially
You can check anytime your logged details by Auth!
Everywhere and from anywhere you can use Auth::user()->id;
example:
for getting logged user id in controller check by!
dd(Auth::user()->id);
If needed just use Illuminate\Support\Facades\Auth in the very beginning of controller.

Getting a vue form to go to the next page after submit in laravel

I'm using both laravel and vue and I'm trying to get my vue form to go to another page when I've submitted, but the problem is that once it's submitted it refreshes and goes back to the page it's on instead of the other page.
When I check my network tab in the dev tools, it posted to the right page but it doesn't show up in the browser
This is my vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Example Component</div>
<div class="card-body">
I'm an Supplier Code Selection component.
<br>
<form #submit.prevent="submit">
<label for="parent-product">Parent Product</label>
<select name="parent-product" id="parent-product" class="form-control" v-model="selected_parent">
<option>Please select your code</option>
<option v-for="product in products" :value="product.id">
{{ product.supplier_code }}
</option>
<option v-for="child in children" :value="child.id">
{{ child.supplier_code }}
</option>
</select>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [
'products',
'children',
'selected_parent'
],
mounted() {
console.log('Component mounted.')
},
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData);
},
},
}
</script>
My route
Route::any('/add-to-cart/{id}', 'PublicController#getAddToCart')->name('product.addToCart');
My controller function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
You could just add a location if the axios call returns success. Ps. untested code.
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then(response => { location: '/'});
},
I found my issue. I forgot to change
return view('public.shopping-cart', compact('supplier_code'));
to
return ['redirect' => route('product.shoppingCart')];
in my laravel controller function

Laravel & Vue.js. I Can't Fix My Code

I'm working on an application to manage some Cvs.
All my resource functions work perfectly (creating and editing new Cvs etc.)
But in my Vue.js part, it's about showing details for every Cv in a show view using Axios to get data from the database or post using a form.
My console shows a reactivity problem about my variables: infos and info.
Here is my show.blade.php code:
#extends('layouts.app')
#section('content')
<div class ="container" id="app">
<div class="container" id="app">
<div class ="row">
<div class="col-md-12">
<div class="panel-panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-md-18"> <h3 class="panel-title"> Experience </h3></div>
<div class="col-md-2 text-right">
<button class="btn btn-success" > Ajouter</button>
</div>
</div>
</div>
<div class="panel-body" >
<ul class="list-group">
<li class="list-group-item" v-for="info in infos">
<div class="pull-right">
<button class="btn btn-warning btn-sm">Edit</button>
</div>
<h3>#{{ info.titre }}</h3>
<p>#{{ info.body }}</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div >
<form class="flex flex-col" #submit.prevent="addExperience">
<textarea class="border rounded p-2 mp-3" v-model="info.titre"></textarea>
<textarea class="border rounded p-2 mp-3" v-model="info.body"></textarea>
<button type="submit" class="border rounded py-2">Commenter</button>
</form>
</div>
</div>
</div>
#endsection
#section('javascripts')
<script src="{{ asset('js/vue.js')}}"> </script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
window.Laravel={!! json_encode([
'csrfToken' => csrf_token(),
'idExperience' => $id,
'url' =>url('/')]) !!} ;
</script>
<script>
var app= new Vue({
el:'#app',
data:{
message: '',
infos: [],
info:{
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
}},
methods:{
getExperiences: function() {
axios.get(window.Laravel.url+'/getexperiences/'+window.Laravel.idExperience)
.then(response=>{
console.log(reponse.data);
this.info=reponse.data;})
.catch(error =>{
console.log('errors: ', error);})},
addExperience:function(){
axios.post(window.Laravel.url+'/addexperience', this.info)
.then(repsonse => {
if(response.data.etat){
this.infos.unshift(this.info);
this.info={
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
};}})
.catch(error =>{
console.log('errors: ', error)})},
created:function(){
this.getExperiences();})};
</script>
#endsection
And my two functions get Experiences and addExperience in CvController:
public function getExperiences($id){
$cv= Cv::find($id);
return $cv->infos;
}
public function addExperience(Request $request){
$info = new Info;
$info->titre=$request->titre;
$info->body=$request->body;
$info->cv_id=$request->cv_id;
$info->save();
return response()->json(['etat'=> true, 'id'=> $info->id]);
}
And these are my routes:
Route::resource('cvs','CvController');
Route::get('/getexperiences/{id}', 'CvController#getExperiences');
Route::post('/addexperience', 'CvController#addExperience');
My console:
There are some syntax errors that need to be fixed first.
There's an extra ")" at the end of your created method
The methods property is missing a closing "}"
There's a missing ")" at the very end to match the opening new Vue( parenthesis.
It's helpful to indent your code to make these things easier to spot.
Then, you'll need to update your data to be a function that returns an object. See Vue Docs - Data Must Be a Function
You also have some typos for the "response" variable.
Lastly, in your HTML you have two divs that have id="app".
Your JS should look something like:
var app = new Vue({
el: '#app',
data: {
message: '',
infos: [],
info: {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
}
},
methods: {
getExperiences: function () {
axios.get(window.Laravel.url + '/getexperiences/' + window.Laravel.idExperience)
.then(response => {
console.log(reponse.data);
this.info = response.data;
})
.catch(error => {
console.log('errors: ', error);
})
},
addExperience: function () {
axios.post(window.Laravel.url + '/addexperience', this.info)
.then(response => {
if (response.data.etat) {
this.infos.unshift(this.info);
this.info = {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
};
}
})
.catch(error => {
console.log('errors: ', error)
})
},
created: function () {
this.getExperiences();
}
}
});
Let me know if that works for you.

laravel API, not fetching data from DB

This is on production side (on unbtu Digital Ocean server)
"laravel: 5.3"
"php": "5.5.9"
Route path : /route/web.php (not in middleware)
Route::get('api/getsymbol-request','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request){
$symbol = DB::table("symbols")
->where("market_id", $request->market_id)
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
http://yourtradelog.com/api/getsymbol-request?market_id=1 //This is not working url I am getting issue WHY THIS IS NOT WORKING
http://yourtradelog.com/api/getsymbol //This is working url
Database tables
<script>
$(document).ready(function() {
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/getsymbol-request/')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
}
});
});
</script>
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbol:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options'] , null, ['class'=>'symbol_id', 'id'=>'symbol','data-width'=>'60%', 'data-live-search'=>'true'] )!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
I prefer using route parameters like this (see more in the documentation here):
Routes:
Route::get('api/getsymbol-request/{id}','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request, $id){
$symbol = DB::table("symbols")
->where("market_id", $id)
->get()
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
Please note that the URL has changed to this format:
http://yourtradelog.com/api/getsymbol-request/1
Try to this code:
public function getSymbolRequest(Request $request)
{
$marketID = (int)$request->get('market_id')
$symbol = DB::table('symbols')
->where('market_id', $marketID)
->get(['symbol','id']);
return response()->json($symbol);
}
public function getSymbol()
{
$symbol = DB::table('symbols')
->get(['symbol','id']);
return response()->json($symbol);
}

Resources