F Moreira
F Moreira

Reputation: 13

I want to send a variable from a Controller to a Trait on Laravel

I have a controller that store the data. This use a form Request and after Show the messages on a trait. I am using the same trait on 3 API but i want to know if is posible send/add to the json/array a Custom Message for each API. For example if Category created (Category created successfull o Product Created Successfull) according the api. This is my Store on my controller

    public function store(StoreCategory $request)
{
    $data = request()->all();
    $newCategory = Category::create($data);    
    return $this->respondCreated(new CategoryResource($newCategory)); 
}

I am using CategoryResource like Resource And this is my trait

    public function respondCreated($data)
{
    return $this->setStatusCode(IlluminateResponse::HTTP_CREATED)->respond($data
    ->response()      
    );
}
    public function respond($data, $headers = [])
{
    $response = $data;
    return $response->setStatusCode($this->statusCode);        
}

CategoryResource code:

public function toArray($request) {
    return [ 'id' => $this->id,
             'name' => $this->name,
             'parent_id' => $this->parent_id,
             'created_at' => $this->created_at,
             'updated_at' => $this->updated_at,
            ];
} 

Is Possible add a custom message per Api Request? May be can i pass a Variable from my controller and after add the custom message add the variable to the array?

Best Regards Sorry my english is not good

Upvotes: 0

Views: 1434

Answers (1)

HM107
HM107

Reputation: 1401

You can achieve this by adding attribute to the model directly : link

Occasionally, when casting models to an array or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:

public function getHasMessageAttribute()
{
    return "the message that you want to pass";
}

After creating the accessor, add the attribute name to the appends property on the model. Note that attribute names are typically referenced in "snake case", even though the accessor is defined using "camel case":

{
/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = ['has_message'];
}

There are many ways to go from here but;

and finally pass the message through CategoryResource

'message'=> $this->has_message,

if you want to separate that from the DB entries you can always use with.

Upvotes: 1

Related Questions