Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return model with laravel when it was created

I need to send a new model saved as json to front but I can't see column organizationid in response

This is my model

class Organization extends Model
{
    protected $table = "core.organizations";
    protected $fillable = ['description'];
    public $primaryKey = "organizationid";
    public $incrementing = false;
    public $timestamps = false;
}

and this is my function

public function saveOrganization(Request $request)
    {
        try {
            $description = $request->input('description');
            $organization = new Organization();
            $organization->description = $description;
            $organization->save();
            if (!$organization) {
                throw new \Exception("No se guardo la organizacion");
            }           
            return response()->json([
            'organization' => $organization,
            ], 200);
        } catch (\Exception $ex) {
            return response()->json([
                'error' => 'Ha ocurrido un error al intentar guardar la organización',
            ], 200);
        }
    }

and this is response

{"organization":{"description":"Restobar"}}

How can I do?

Thanks you!!

like image 367
Michael Zapata Avatar asked Jul 30 '17 20:07

Michael Zapata


1 Answers

Since you've created a new object, and not retrieved one from the database, the only attributes it will know about are the ones that you set.

If you'd like to get the rest of the fields on the table, you will need to re-retrieve the object after you save it.

// create the new record.
// this instance will only know about the fields you set.
$organization = Organization::create([
    'description' => $description,
]);

// re-retrieve the instance to get all of the fields in the table.
$organization = $organization->fresh();
like image 198
patricus Avatar answered Oct 11 '22 14:10

patricus