How can I create a Laravel Resource relationship for a belongsTo? - laravel

I have created a UserResource that is successfully returning all of my user attributes, including the organization it belongs to. It looks something like this:
Resources/User.php
return [
'type' => 'users',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
'email' => $this->email,
...
'relationships' => [
'organization' => $this->organization,
],
];
In my User model, there is a belongsTo relationship for User->Organization.
Instead of returning the actual organization model, I'd like to return the organization resource.
For example, an organization hasMany locations:
Resources/Organization.php
return [
'type' => 'organizations',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
...
'relationships' => [
'locations' => Location::collection($this->locations),
],
];
I can successfully return the collection of locations that belong to the organization. I have not been able to return a belongsTo relationship.
I've tried:
Resources/User.php
'relationships' => [
'organization' => Organization::collection($this->organization),
],
// or this
'relationships' => [
'organization' => Organization::class($this->organization),
],
// or this
use App\Http\Resources\Organization as OrganizationResource;
...
'relationships' => [
'organization' => OrganizationResource($this->organization),
],
How can I return a single model as a related resource? Thank you for any suggestions!

Have you tried it with the new keyword?
'relationships' => [
'organization' => new OrganizationResource($this->organization),
],

Related

Standard RESTful controller or model ignores PUT verb in Yii 2

tl;dr I have followed the official guide. Everything seems working except for PUT/PATCH verb. The 200 OK code is returned, but the actual model isn't updated. What can be wrong?
I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for PATCH /users/123 / PUT /users/123. When executed in Insomnia, I am getting 200 OK, but the returned record shows no sign of modification:
What can be wrong or what am I missing?

can i use stripe checkout with destination charges?

I'm wondering if there is any way to charge some kind of fee on transactions using the new Stripe Checkout system. In this particular instance I am using Laravel 8 with Livewire. In my component I have a function tied to a button called setStripeSession.
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'Custom Media',
],
'unit_amount' => $this->toPennies($price),
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => 'http://e68ec3e6b8b2.ngrok.io/',
'cancel_url' => 'http://e68ec3e6b8b2.ngrok.io/',
],['stripe_account_id'=>$this->stripe_account_id]);
$this->stripe_session_id = $session->id;
Message::where('id',$message_id)->update(['stripe_session_id'=>$this->stripe_session_id ]);
$this->emit('PayonStripe',['ssid'=>$session->id]);
}
I imagined adding something like the below code but the variables are not recognized by the stripe API during the rquest.
'transfer_data' => [
'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}',
],
Yes! You can set these within the payment_intent_data parameter:
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [...],
'mode' => 'payment',
'success_url' => 'http://example.com/success',
'cancel_url' => 'http://example.com/cancel',
'payment_intent_data' => [
'application_fee_amount' => 100, // optional
'transfer_data' => [
'destination' => 'acct_123',
],
],
]);
A number of parameters are exposed this way in Checkout, such as metadata for the payment intent and similar data for subscription mode under subscription_data.

How to add fields which are not available in database?

I am not able to add field which is not available in my database
I have tried adding
$this->crud->addFields([
[
'name' => 'coupon_type',
'label' => 'Coupon For',
'type' => 'select_from_array',
'options' => [
// Options
],
'allows_null' => true,
'default' => 1,
'attributes' => [
'id' => 'coupon_type'
]
]
]);
I want to add fields in my create page.
You can do this by defining accessors for your "virtual" attributes
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
and defining the appends on your model
protected $appends = ['is_admin'];
Find everything in the docs here:
https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json

mapWithKeys in laravel ,i dont understand how do it work?

I saw the example of laravel, but i dont understand how do it work.
for this example:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
someone can explain detail of it?
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
//this line takes one array of collection object in item array and make a key of its email and store name on that email key
return [$item['email'] => $item['name']];
});
$keyed->all();

Laravel validation unique subcatetory with diferent category

I want to determine the field unique in laravel with the follow code:
This is the validation to the table product_subcategories:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'name' => 'required|unique:product_subcategories|max:255',
'product_categories_id' => 'required'
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'name' => 'required|unique:product_subcategories|max:255',
'product_categories_id' => 'required'
]
];
But I want that the field name be unique with the product_categories_id, for example, it cant be unique if the name of the field is the same but with product_categories_id is different each other. How can I do this?
You can specify the column to compare to with the second parameter of the rule.
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'name' => 'required|unique:product_subcategories,name|max:255',
'product_categories_id' => 'required'
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'name' => 'required|unique:product_subcategories,name|max:255',
'product_categories_id' => 'required'
]
]
This example will be checking if there is any other field in product_subcategories with the same name.
For update, you can extend this with a third parameter which is the value of the name you want to ignore. (So you can save the SubCategory without changing it's name.)

Resources