I need to foreach array from session. My controller code
return [
'buys' => request()->session()->get('userBuys')
];
Vue component
export default {
data() {
return {
buys: {}
}
},
methods: {
async getBuys() {
this.$axios.post('/products/mybuys')
.then(res => {
this.buys = res.data.buys
this.$root.hideLoading()
})
}
},
mounted() {
this.$root.showLoading()
this.getBuys()
}
}
So i'm getting array
How i need to foreach this array correctly? I tried a lot of...
You have a json in a array so your
buys = [113, 114,...]
So your loop have only the numbers not the propertys/attributes
Try without brackets:
return 'buys' => request()->session()->get('userBuys')
Related
My Code is like below.
$prayers = Prayer_time::where('mosque_id', $request->mosque_id)
->where('month', $month)
->where('date', $date)
->first();
foreach ($prayers as $key => $prayer) {
if ($prayer != null) {
$payer_times[$key] = $prayer;
}
}
return response()->json(['prayer_times' => $payer_times], 200);
I am getting below output.
{
"prayer_times": {
"incrementing": true,
"exists": true,
"timestamps": true
}
}
How can I iterate through result?
Assuming that first one is an API Controller and you want to iterate over the prayer_times in a frontend
res.data.prayers_time.each({
DO WHATEVER
})
My code looks like this
child component.vue
<script>
export default {
props: ['Pconvs_id'],
data(){
return{
user : '',
messages:[],
newMessage : '',
convs_id: '',
}
},
created(){
this.convs_id = this.Pconvs_id;
this.fetchMessages();
},
methods:
{
fetchMessages()
{
console.log(this.convs_id);
axios.get('messages',{cons_id: this.convs_id}).then(response=> {
this.messages = response.data;
});
axios.get('authuser').then(response=>{
this.user = response.data;
});
},
},
watch: {
// whenever convs_id changes, this function will run
Pconvs_id: function (newConvs_id, oldConvs_id) {
this.convs_id = newConvs_id;
this.fetchMessages();
}},}
</script>
parent component.vue
<Message :Pconvs_id="convs_id"/>
my problem is that even when the convs_id changed fetchmessage() return same data what did i do wrong
axios call handler
public function fetchmessages(Request $cons_id)
{
return Message::where([
['cons_id' , $cons_id],
])->with('user')->get();
}
Elequent relationship
message model beongsTo user and User hasMany message
I think your backend handler receives an instance of Illuminate\Http\Request
so to get the cons_ids you should to something like
public function fetchmessages(Request $request)
{
// Get the cons_id from the request object
$cons_id = $request->get('cons_id');
// Cleaned up your "where" query
return Message::where('cons_id', $cons_id)->with('user')->get();
}
I am follow this Link for a inertiaJS tutorial. BTW I'm using laravel 8
I have this image below from my webpage. I don't know why I don't have a page>errors in picture given. Is there any other way to validate a form other than the link that I provided?.
I commented out the page.error in my HTML because it causes me an error Error in render: "TypeError: Cannot read property 'email' of undefined" because of my Page.Error is an empty object.
Update : Code for my controller
Script Code
<script>
import Layout from "../../Shared/Layout";
export default {
components: {
Layout,
},
data() {
return {
lead: {
name: "",
email: "",
phone: "",
dob: "",
interested_package: "",
},
};
},
methods: {
async handleSubmit() {
let res = await this.$inertia.post("/leads/save", this.lead);
},
},
};
</script>
App Service Provider
public function boot()
{
//
Schema::defaultStringLength(255);
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessage()
: (object)[];
}
]);
Inertia::share('flash', function () {
return [
'message' => Session::get('message'),
'success' => Session::get('success'),
'error' => Session::get('error'),
];
});
}
To access the email error, context needs to be added via the this keyword ie. this.$page.props.errors.email.
Hey i think you are not sharing error bag in Controller that is why is empty ,to solve this, go to your AppServiceProvider
and add this code.
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessages()
: (object) [];
},
]);
i have an array values in update form. i need to update specific values when user change in textareas. it looks like this
In my vuejs data objects looks like this.
data() {
return {
jobs: [],
details: {
basic_id: this.$route.params.id,
work: this.jobs
}
};
},
and my update method i wrote like this.
updateDetails() {
this.loading = true;
this.updateWorkedPlaces(this.details)
.then(() => {
console.log("success");
this.loading = false;
})
.catch(() => {
this.loading = false;
});
}
i pass these values it my vuex action methods.
async updateWorkedPlaces({ commit }, payload) {
let job = await Api().put("works/" + payload.basic_id, payload.work);
commit("UPDATE_WORK", job);
},
i pass these values to my laravel backend update function. it looks like this.
public function update(Request $request, $id)
{
$work = $request->work;
$basic = $request->basic_id;
foreach ($request->work as $i => $id) {
$job = Job::findOrFail($basic);
$job->fill(['position' => $id['position'], 'address' => $id['address']])->save();
}
return response()->json(['message' => 'success']);
}
but when i pass these values to this function it shows me this error.
Invalid argument supplied for foreach()
how can i fix this error. anyone can help me?
i figure out my problem with this function
public function update(Request $request, $id)
{
$collection = $request->all();
for ($i = 0; $i < count($collection); $i++) {
Job::where('id', $collection[$i]['id'])
->update([
'position' => $collection[$i]['position'],
'address' => $collection[$i]['address']
]);
}
return response()->json(['collection' => $collection]);
}
I have more then 8000 records in DB. I need a solid pagination and filtering functionality. To accomplish that I am trying to filter the records before paginate and send out those to endpoint.
For example in controller I request the keyword and check the keyword using →when() if there is keyword then filter records with that and →paginate(20)
in controller
public function bridal(Request $request)
{
$keyword = $request->get("keyword");
$bridals = Place::with(["plans" => function($query)
{
$query->orderBy("plans.plan_price");
}
])
->whereHas("plans")
->groupBy("address")
->when($keyword, function($query, $keyword){
return $query->where("city", $keyword);
})
->paginate(20);
return $bridals;
}
Route
Route::match(["GET", "POST"], "bridal", "Api\BridalController#bridal");
I guess everything is fine 'till here. So let's continue in frontend side.
in vuex: Store.js
state: {
bridals: [],
keyword: "",
},
mutations: {
setBridals(state, bridal){
state.bridals = bridal;
},
setKeywords(state, keys){
state.keyword = keys;
},
},
getters: {
getBridals(state){
return state.bridals;
},
},
actions: {
bridalApi({commit}, payload){
axios.get("api/bridal?page="+payload.page, {
keyword: payload.forms.keyword
})
.then(response => {
this.commit("setBridals", response.data);
})
.catch(e => {
console.log(e);
})
},
}
and in home component I am sending filter params to controller.
<form #submit.prevent="submit" method="post">
<search-bar />
<submit-btn />
</form>
mounted(){
this.$store.dispatch("bridalApi", {
page: this.currentPage,
forms: this.filterParams,
});
},
methods: {
submit(){
this.$store.dispatch("bridalApi", {
forms: this.filterParams,
});
},
},
computed: {
filterParams(){
let paramObj = {
keyword: this.$store.state.bridal.keyword,
}
return paramObj;
}
},
I am not sure what is wrong in the code. Where do I make mistake.
P.S: By the way I set and get the keyword state.keyword... it's working fine. I can get the value. I just didn't add input code here...