Laravel vue cannot access to relation data - laravel

I have customer data which has hasOne relationship with address table.
Returned data format is like below.
{
"customer_id": 1,
"last_name": "Cruickshank",
"first_name": "Pearl",
"phone": "+4 921-008-8344",
"email": "kristofer.kautzer#example.org",
"order_id": null,
"address_id": 66,
"created_at": "2017-01-18 06:24:40",
"updated_at": "2017-01-18 06:24:40",
"deleted_at": null,
"address": {
"address_id": 1,
"address_code": "RS-03549-9811",
"address1": "14978 Effertz Turnpike Apt. 086",
"address2": null,
"city": "Susanaburgh",
"province": "Illinois",
"country": "PG",
"postal_code": "03549-9811",
"created_at": "2017-01-18 06:24:40",
"updated_at": "2017-01-18 06:24:40"
}
I got data using return $this->model->with(implode(',', $relation))->get();
However, I cannot access any of data in address object.
Vue Code
I throw city is undefined. However, I can access to address object data using chrome developer tool
<tr v-for="(customer, index) in customers">
<td>{{index + 1}}</td>
<td>{{getFullName(customer.first_name, customer.last_name)}}</td>
<td>{{customer.phone}}</td>
<td>{{customer.address.city}}</td>
</tr>
Am I doing something wrong? I tried customer['address']['city'] as well.
I can access city when I get data as you see below.
getCustomerList () {
axios.get('/api/customers')
.then((res)=>{
if(res.status === 200){
//I can access city here but not in vue for loop ...
console.log(res.data.customers[0].address.city)
this.customers = res.data.customers
}
})
},

Related

Validation of each field in JSON response using karate API

I want to validate particular fields in the response whether it is integer or float(ex: fullbathrooms field). I tried below code but getting match failed error. Could you please help here ?.....Thanks
Given path '/property-client'
And request {"address": <address>,"city": <city>,"state": <state>,"zipCode": <zipCode>}
When method post
Then status 200
And print response
And match response == {fullbathrooms:'#number'}
Examples:
|read('testFile1.csv')|
Error : match failed: EQUALS
Actual response:
{
"success": true,
"message": {
"version": "1.0",
"response": {
"id": "94568859",
"type": "express",
"responseheader": null,
"reportdata": {
"property": {
"source": null,
"type": null,
"dom": null,
"propertytype": "Single Family Residence",
"standardtype": null,
"address": {
"documentid": null,
"number": "150",
"directional": null,
"street": "BRIDGE",
"suffix": "RD",
"postdirectional": null,
"unit": "",
"city": "HILLSBOROUGH",
"state": "CA",
"zip": "94010",
"zipplus4": "6908",
"fulladdress": "150 BRIDGE RD, HILLSBOROUGH, CA 94010"
},
"info": {
"type": null,
"fips": "6081",
"county": "San Mateo",
"bedrooms": "5",
"bathrooms": "6.50",
"fullbathrooms": "6.50",
"totalrooms": "0",
"livingarea": "7750",
"totallivingarea": "7750",
"landarea": "41382",
"landareatype": null,
"pool": "true",
"landvalue": "6904800",
"improvementvalue": "3284414",
"assessedvalue": "10189214",
"assessedyear": "2021",
"taxvalue": "11746898",
"taxyear": "2021",
"deliquentyear": null,
"yearbuilt": "2011",
"propertytax": null,
"approxage": "11",
"parcelnumber": "032-400-110",
"titlecompany": null,
"geocode": {
"latitude": "37.563272",
"longitude": "-122.334442",
"geoqualitycode": ""
}
}
Please take some time to read the documentation: https://github.com/karatelabs/karate#match-contains
I'm not going to refer to your response dump (which by the way is not valid JSON), but give you a simple example. Please pay attention to the structure of your JSON. And note that the 6.50 is a string not a number in your response.
* def response = { "foo": { "bar": { "fullbathrooms": "6.50" } } }
* match response.foo.bar == { fullbathrooms: '#string' }
If you want to validate numbers within strings, please refer other answers, for example: https://stackoverflow.com/search?q=%5Bkarate%5D+number+regex

How to Users of a specific Room and filter these users with specific spatie tag?

I have a User model that have spatie tags (developer and consultant).
I have a Room model that have many to many relation with User.
I want to return users of a specific room with tag of "consultant".
Can you please help me to do that?
I can find my specific room by id and also I can use relation to get its users but I dont know how to filter them by tag.
I hope you understand my point.
this is what I tried so far but didnt worked!
$room->users->withAnyTags('consultant');
here is my relation:
public function users()
{
return $this->belongsToMany(User::class, 'skyroom_room_user', 'skyroom_room_id', 'user_id')->with('tags');
}
if I run this:
$room->users;
it will return this:
{
"id": "2c8fdf5a-fe94-4216-a3dc-8a49e76c6e34",
"first_name": null,
"last_name": null,
"email": null,
"slug": null,
"username": "+989353785968",
"gender": "male",
"birthday": null,
"national_code": null,
"sheba": null,
"country": null,
"city": null,
"bio": null,
"long_bio": null,
"education": null,
"language": null,
"type": "trainee",
"avatar": null,
"verified_at": null,
"certified_at": null,
"referred_by": null,
"referred_at": null,
"skyroom_user_id": 9379122,
"skyroom_username": "09353785968",
"skyroom_nickname": "مصطفی طاهری",
"skyroom_access": 1,
"created_at": "2021-04-08T13:22:42.000000Z",
"updated_at": "2021-04-08T13:22:42.000000Z",
"deleted_at": null,
"tags": []
},
{
"id": "33b1a31d-1aae-4c38-8c07-0793de5a4216",
"first_name": "حامد",
"last_name": "پوسانه",
"email": "h.pousaneh#gmail.com",
"slug": "hamed",
"username": "+989127426900",
"gender": "male",
"birthday": "1990-05-28 19:37:12",
"national_code": null,
"sheba": null,
"country": "Iran",
"city": "Tehran",
"bio": "مدیریت کسب و کار",
"long_bio": "مدیریت کسب و کار از دانشگاه صنعتی امیرکبیر",
"education": "کارشناسی ارشد",
"language": "فارسی، آذری و انگلیسی",
"type": "trainer",
"avatar": null,
"verified_at": null,
"certified_at": null,
"referred_by": "a9ca25bd-18fb-4271-8155-0a75d9dc31d9",
"referred_at": null,
"skyroom_user_id": 8025480,
"skyroom_username": "09127426900",
"skyroom_nickname": "حامد پوسانه",
"skyroom_access": 3,
"created_at": "2021-04-08T13:06:24.000000Z",
"updated_at": "2021-04-08T15:07:13.000000Z",
"deleted_at": null,
"tags": [
{
"id": "71de78b1-15ad-410d-9778-50cb9b3bd4ca",
"name": {
"en": "consultant"
},
"slug": {
"en": "consultant"
},
"type": "user-system-tag",
"order_column": 3,
"created_at": "2021-04-08T13:06:24.000000Z",
"updated_at": "2021-04-08T13:06:24.000000Z",
"pivot": {
"taggable_id": "33b1a31d-1aae-4c38-8c07-0793de5a4216",
"tag_id": "71de78b1-15ad-410d-9778-50cb9b3bd4ca",
"taggable_type": "App\\Models\\User"
}
},
Assuming you have created your relationships correctly, the syntax for retrieving tagged models would be:
$room->users()->withAnyTags('consultant')->get()
If you wanted to search for multiple tags, you would provide an array to withAnyTags:
$room->users()->withAnyTags(['consultant', 'developer'])->get()

Paginate on grouped queries

I'm writing a system to follow cash flow. The users register transactions they made:
(transactions index screenshot)
but I need to get these transactions separated by date. I tried using an Request to index, but it doesn't looked the best pratice (it worked, however). Now I'm trying to do another aproach: retrieve all transactions and paginate them by date. Is it possible?
ps: maybe grouping by months helps? like:
$transactions = Transaction::all()->groupBy(function($transaction) {
return Carbon::parse($transaction->date)->format('m-Y');
});
this returns:
{
"03-2019": [
{
"id": 1,
"title": "Teste 1",
"date": "2019-03",
"user_id": 1,
"description": "Primeiro teste, com entrada de 1500 reais.",
"value": "1500.00",
"flow": 1,
"created_at": "2019-03-24 05:39:45",
"updated_at": "2019-03-24 05:39:45"
},
{
"id": 2,
"title": "Teste 2",
"date": "2019-03",
"user_id": 1,
"description": "Segundo teste, com saída de 500 reais.",
"value": "500.00",
"flow": 0,
"created_at": "2019-03-24 05:39:45",
"updated_at": "2019-03-24 05:39:45"
}
]
}
ps²: yeah, front-end is in brazilian portuguese and english isn't my native language.. :)
Try this out
<?php
use Illuminate\Pagination\LengthAwarePaginator;
$transactions = Transaction::all()->groupBy(function($transaction) {
return Carbon::parse($transaction->date)->format('m-Y');
});
//new LengthAwarePaginator($data,$countOfData,$perPage,$currentPage);
$transactions=new LengthAwarePaginator($transactions->forPage($currentPage,$perPage),$transactions->count(),$currentPage);
Hope it helps...

Laravel, appending an attribute to a returned json appends the entire object

I have 2 tables Customer(Parent) and jobCode(Child) with one to many relationships
I want to retrieve a child record but with one extra field from the parent (customerGuid) as well. My code:
$jobCodes=JobCode::all();
foreach ($jobCodes as $jobCode) {
$jobCode['customerGuid']=$jobCode->customer->guid;
// I also tried $jobCode->setAttribute('customerGuid',$jobCode->customer->guid);
}
return $jobCodes;
I was expecting just the parent's guid field to be appended to each jobCode object and returned. However the ENTIRE customer parent object is returned!
[{
"id": 137,
"customerId": 1,
"jobCode": "Journeyman Plumber",
"jobDescription": "Journeyman Plumber",
"created_at": null,
"updated_at": "2017-01-27 12:20:27",
"guid": "28f35e94-e483-11e6-98e9-e0db55883624",
"customerGuid": "8d48931d-dc61-11e6-8927-e0db55883624",
"customer": {
"id": 1,
"name": "ACME",
"address1": "",
"address2": "",
"city": "San Jose",
"zip": "",
"phone": "",
"fax": "",
"email": "",
"guid": "8d48931d-dc61-11e6-8927-e0db55883624",
"stateName": "California",
"created_at": null,
"updated_at": "2017-01-20 07:10:59"
}
}, {
"id": 138,
"customerId": 1,
"jobCode": "JRP PreFab",
"jobDescription": "JRP",
......,
Its because your return statement returns $jobCodes; which is the entire table you retrieve here: $jobCodes=JobCode::all();
try putting this inside your loop
echo '$jobCode' to see what is the output every time it loops
Reaching for the relationship customer on $jobCode you automatically lazy load the relationship object, which is stored in $jobCode->customer attribute.
Try this instead just returning the collection:
// return $jobCodes;
return $jobCodes->map(function($jobCode){
$jobCode = $jobCode->toArray();
unset($jobCode['customer']);
return $jobCode;
});

Laravel Cashier: Resume a single payment

after a successful payment I store the stripe id on a mysql table. With that id I would like to retrieve all the details stored in the stripe database.
So is it possible to resume a single payment by the stripe id?
Thanks
Here is the documentation you need to use: https://stripe.com/docs/api/php#retrieve_customer
Use the "customer retrieve" Stripe API call to retrieve details about the customer's purchase:
Stripe::setApiKey(Config::get('your_stripe_secret_key_here'));
$customer_object = Customer::retrieve(customers_stripe_id);
This will return the following JSON:
Stripe\Customer JSON: {
"id": "cus_7KJZQ8Z6jfSSMl",
"object": "customer",
"account_balance": 0,
"created": 1447172728,
"currency": "usd",
"default_source": "card_175evz2eZvKYlo2CKoS2WEDk",
"delinquent": false,
"description": "Bingo|www|0c1234567890",
"discount": null,
"email": null,
"livemode": false,
"metadata": {
},
"shipping": null,
"sources": {
"object": "list",
"data": [
{
"id": "card_175evz2eZvKYlo2CKoS2WEDk",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": "cus_7KJZQ8Z6jfSSMl",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 5,
"exp_year": 2016,
"funding": "credit",
"last4": "4242",
"metadata": {
},
"name": null,
"tokenization_method": null
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/customers/cus_7KJZQ8Z6jfSSMl/sources"
},
"subscriptions": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_7KJZQ8Z6jfSSMl/subscriptions"
}
}
Here is Stripe's version of the API call:
\Stripe\Stripe::setApiKey("your_secret_key");
\Stripe\Customer::retrieve("the_customers_id");
Make sure to import the \Stripe classes by adding this at the top of your Model or Controller:
use Stripe\Customer;
use Stripe\Stripe;
if you want to use "Stripe" instead of \Stripe\Stripe and \Stripe\Customer prefixes)

Resources