### Get Database Instance using Orm Facade Source: https://www.goravel.dev/orm/getting-started Illustrates how to obtain a database instance for performing query operations using the `Query` method of the `facades.Orm()`. This can be chained with `Connection` or `WithContext`. ```go facades.Orm().Query() facades.Orm().Connection("mysql").Query() facades.Orm().WithContext(ctx).Query() ``` -------------------------------- ### Interact with Generic Database Interface sql.DB using Orm Facade Source: https://www.goravel.dev/orm/getting-started Provides examples of obtaining the generic `sql.DB` interface from the ORM facade to perform low-level database operations like pinging, closing connections, and configuring connection pool settings. ```go db, err := facades.Orm().DB() db, err := facades.Orm().Connection("mysql").DB() // Ping db.Ping() // Close db.Close() // Returns database statistics db.Stats() // SetMaxIdleConns sets the maximum number of connections in the idle connection pool db.SetMaxIdleConns(10) // SetMaxOpenConns sets the maximum number of open connections to the database db.SetMaxOpenConns(100) // SetConnMaxLifetime sets the maximum amount of time a connection may be reused db.SetConnMaxLifetime(time.Hour) ``` -------------------------------- ### Inject Context using Orm Facade Source: https://www.goravel.dev/orm/getting-started Demonstrates how to inject a context into the ORM facade for operations that require it, such as database queries with timeouts or cancellations. ```go facades.Orm().WithContext(ctx) ``` -------------------------------- ### Restore Source: https://www.goravel.dev/orm/getting-started Restores soft-deleted records. ```APIDOC ## RESTORE ### Description Restores soft-deleted records. ### Method PUT ### Endpoint `/api/orm/restore/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the record to restore. #### Request Body - **model** (string) - Required - The model of the record to restore. ### Request Example ```json { "model": "models.User" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful restoration. #### Response Example ```json { "message": "Record restored successfully." } ``` ``` -------------------------------- ### Retrieving or Creating Models Source: https://www.goravel.dev/orm/getting-started Explains the FirstOrCreate and FirstOrNew methods for finding existing records or creating new ones if they don't exist. ```APIDOC ## POST /query/retrieve-or-create ### Description Finds a record by attributes or creates a new one if it doesn't exist. FirstOrNew returns a new instance without saving, while FirstOrCreate saves it. ### Method POST ### Endpoint `/query/retrieve-or-create` ### Parameters #### Request Body - **gender** (integer) - Required - The gender to filter or create by. - **name** (string) - Required - The name to filter or create by. - **avatar** (string) - Optional - The avatar to set if creating a new record. ### Request Example ```go // FirstOrCreate example var user models.User facades.Orm().Query().Where("gender", 1).FirstOrCreate(&user, models.User{Name: "tom"}) // SELECT * FROM `users` WHERE `gender` = 1 AND `users`.`name` = 'tom' ORDER BY `users`.`id` LIMIT 1; // INSERT INTO `users` (`created_at`,`updated_at`,`name`) VALUES ('2023-09-18 12:51:32.556','2023-09-18 12:51:32.556','tom'); facades.Orm().Query().Where("gender", 1).FirstOrCreate(&user, models.User{Name: "tom"}, models.User{Avatar: "avatar"}) // SELECT * FROM `users` WHERE `gender` = 1 AND `users`.`name` = 'tom' ORDER BY `users`.`id` LIMIT 1; // INSERT INTO `users` (`created_at`,`updated_at`,`name`,`avatar`) VALUES ('2023-09-18 12:52:59.913','2023-09-18 12:52:59.913','tom','avatar'); // FirstOrNew example var user models.User facades.Orm().Query().Where("gender", 1).FirstOrNew(&user, models.User{Name: "tom"}) // SELECT * FROM `users` WHERE `gender` = 1 AND `users`.`name` = 'tom' ORDER BY `users`.`id` LIMIT 1; facades.Orm().Query().Where("gender", 1).FirstOrNew(&user, models.User{Name: "tom"}, models.User{Avatar: "avatar"}) // SELECT * FROM `users` WHERE `gender` = 1 AND `users`.`name` = 'tom' ORDER BY `users`.`id` LIMIT 1; ``` ### Response #### Success Response (200) - **user** (models.User) - The found or newly created user instance. #### Response Example ```json { "id": 1, "name": "tom", "gender": 1, "avatar": "avatar" } ``` ``` -------------------------------- ### Specify Database Connection using Orm Facade Source: https://www.goravel.dev/orm/getting-started Shows how to select a specific database connection from multiple configured connections in `config/database.go` using the `Connection` method of the `facades.Orm()`. ```go facades.Orm().Connection("mysql") ``` -------------------------------- ### Start New Session with Goravel Source: https://www.goravel.dev/the-basics/session Provides a code example for initiating a new session using a driver instance obtained from the session manager. ```go session := facades.Session().BuildSession(driver) session.Start() ``` -------------------------------- ### Conditional Query Clauses Source: https://www.goravel.dev/orm/getting-started Demonstrates various methods for building complex query conditions, including equality, ranges, inclusion/exclusion, null checks, and OR conditions. ```go facades.Orm().Query().Where("name", "tom") facades.Orm().Query().Where("name = 'tom'") facades.Orm().Query().Where("name = ?", "tom") facades.Orm().Query().WhereBetween("age", 1, 10) facades.Orm().Query().WhereNotBetween("age", 1, 10) facades.Orm().Query().WhereNotIn("name", []any{"a"}) facades.Orm().Query().WhereNull("name") facades.Orm().Query().WhereIn("name", []any{"a"}) facades.Orm().Query().OrWhere("name = ?", "tom") facades.Orm().Query().OrWhereNotIn("name", []any{"a"}) facades.Orm().Query().OrWhereNull("name") facades.Orm().Query().OrWhereIn("name", []any{"a"}) ``` -------------------------------- ### Perform Joins in Goravel ORM Source: https://www.goravel.dev/orm/getting-started Shows how to join tables in Goravel ORM using the `Join` method. It supports different join types like 'left join' and allows selecting columns from multiple tables. ```go type Result struct { Name string Email string } var result Result facades.Orm().Query().Model(&models.User{}).Select("users.name, emails.email").Join("left join emails on emails.user_id = users.id").Scan(&result) // SELECT users.name, emails.email FROM `users` LEFT JOIN emails ON emails.user_id = users.id; ``` -------------------------------- ### Generate SQL Queries in Goravel ORM Source: https://www.goravel.dev/orm/getting-started Demonstrates how to generate SQL queries with placeholders or raw values using `ToSql` and `ToRawSql` methods in Goravel ORM. This is useful for debugging and understanding the generated SQL. ```go facades.Orm().Query().ToSql().Get(models.User{}) // SELECT * FROM "users" WHERE "id" = $1 AND "users"."deleted_at" IS NULL facades.Orm().Query().ToRawSql().Get(models.User{}) // SELECT * FROM "users" WHERE "id" = 1 AND "users"."deleted_at" IS NULL The methods can be called after `ToSql` and `ToRawSql`: `Count`, `Create`, `Delete`, `Find`, `First`, `Get`, `Pluck`, `Save`, `Sum`, `Update`. ``` -------------------------------- ### Run 'db:show' Artisan Command (Go) Source: https://www.goravel.dev/upgrade/v1.15 Shows how to execute the `db:show` Artisan command in Goravel to view information about the configured database connections. This command is useful for debugging and understanding database setup. ```bash go run . artisan db:show ``` -------------------------------- ### Starting Queue Workers with Custom Parameters (Go) Source: https://www.goravel.dev/digging-deeper/queues Demonstrates how to configure and start multiple queue workers with specific parameters. This allows for monitoring different queues, setting connection names, and defining concurrency levels for each worker. ```go // No parameters, default listens to the configuration in the `config/queue.go`, and the number of concurrency is 1 go func() { if err := facades.Queue().Worker().Run(); err != nil { facades.Log().Errorf("Queue run error: %v", err) } }() // Monitor processing queue for redis link, and the number of concurrency is 10 go func() { if err := facades.Queue().Worker(queue.Args{ Connection: "redis", Queue: "processing", Concurrent: 10, }).Run(); err != nil { facades.Log().Errorf("Queue run error: %v", err) } }() ``` -------------------------------- ### Get Database Driver in Goravel Source: https://www.goravel.dev/orm/getting-started This snippet shows how to retrieve the name of the currently configured database driver using the Goravel ORM. It also provides an example of how to check the driver against known constants like `orm.DriverMysql`. ```go driver := facades.Orm().Query().Driver() // Judge driver if driver == orm.DriverMysql {} ``` -------------------------------- ### Goravel Application Entry Point and Server Startup (Go) Source: https://www.goravel.dev/architecture-concepts/request-lifecycle The main.go file is the entry point for Goravel applications. It initializes the framework using bootstrap.Boot(), creates a new application instance, boots service providers and configurations, and finally starts the HTTP server. This process ensures the application is ready to handle incoming requests. ```go package main import ( "github.com/goravel/framework/facades" "github.com/goravel/framework/support/bootstrap" ) func main() { // Initialize the framework bootstrap.Boot() // Create a new application instance app := foundation.NewApplication() // Boot service providers and configurations app.Boot() config.Boot() // Start the HTTP server facades.Route().Run(facades.Config().GetString("app.host")) } ``` -------------------------------- ### Create Records in Goravel ORM Source: https://www.goravel.dev/orm/getting-started Illustrates how to create single records in the database using Goravel ORM, either by passing a model struct or a map. It also shows how to create records without triggering model events. ```go user := models.User{Name: "tom", Age: 18} err := facades.Orm().Query().Create(&user) // INSERT INTO users (name, age, created_at, updated_at) VALUES ("tom", 18, "2022-09-27 22:00:00", "2022-09-27 22:00:00"); // Not trigger model events err := facades.Orm().Query().Table("users").Create(map[string]any{ "name": "Goravel", }) // Trigger model events err := facades.Orm().Query().Model(&models.User{}).Create(map[string]any{ "name": "Goravel", }) ``` -------------------------------- ### Custom Filesystem Driver Configuration (Go) Source: https://www.goravel.dev/digging-deeper/filesystem Configuration example for setting up a custom filesystem driver in `config/filesystems.go`. Requires implementing the `Driver` interface. ```go "custom": map[string]any{ "driver": "custom", "via": filesystems.NewLocal(), }, ``` -------------------------------- ### Querying Multiple Records Source: https://www.goravel.dev/orm/getting-started Demonstrates how to retrieve multiple records based on specified criteria using the Where and Get methods. ```APIDOC ## GET /query/multiple ### Description Retrieves multiple records from the database based on given conditions. ### Method GET ### Endpoint `/query/multiple` ### Parameters #### Query Parameters - **ids** (array[integer]) - Required - A list of IDs to filter the users. ### Request Example ```go var users []models.User facades.Orm().Query().Where("id in ?", []int{1,2,3}).Get(&users) // SELECT * FROM `users` WHERE id in (1,2,3); ``` ### Response #### Success Response (200) - **users** (array[models.User]) - A list of user records matching the criteria. #### Response Example ```json [ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane@example.com" } ] ``` ``` -------------------------------- ### Start HTTPS Server in Go Source: https://www.goravel.dev/the-basics/routing Starts the Goravel HTTPS server using facades.Route().RunTLS() or facades.Route().RunTLSWithCert(). Ensure http.tls configuration in config/http.go is complete for RunTLS(). RunTLSWithCert() allows custom host and certificate configuration. ```go // main.go if err := facades.Route().RunTLS(); err != nil { facades.Log().Errorf("Route run error: %v", err) } ``` ```go // main.go if err := facades.Route().RunTLSWithCert("127.0.0.1:3000", "ca.pem", "ca.key"); err != nil { facades.Log().Errorf("Route run error: %v", err) } ``` -------------------------------- ### Add Localization Configuration (Go) Source: https://www.goravel.dev/upgrade/v1.14 Example of adding configuration items for the localization module to the 'config/app.go' file. This includes setting default and fallback locales and registering the ServiceProviders for session and translation. ```go "locale": "en", "fallback_locale": "en", "providers": []foundation.ServiceProvider{ ... &session.ServiceProvider{}, &translation.ServiceProvider{}, ... } ``` -------------------------------- ### Limit Query Results Source: https://www.goravel.dev/orm/getting-started Restricts the number of records returned by a query. The `Limit` method is often used in conjunction with `Where` and `Get`. ```go var users []models.User facades.Orm().Query().Where("name = ?", "tom").Limit(3).Get(&users) ``` -------------------------------- ### Start HTTP Server in Go Source: https://www.goravel.dev/the-basics/routing Starts the Goravel HTTP server using facades.Route().Run(). It bootstraps the framework and logs any errors encountered during server startup. This function is typically called in the main function of an application. ```go package main import ( "github.com/goravel/framework/facades" "goravel/bootstrap" ) func main() { // This bootstraps the framework and gets it ready for use. bootstrap.Boot() // Start http server by facades.Route(). go func() { if err := facades.Route().Run(); err != nil { facades.Log().Errorf("Route run error: %v", err) } }() select {} } ``` -------------------------------- ### Execute Native SQL in Goravel Source: https://www.goravel.dev/orm/getting-started This section explains how to execute raw, native SQL queries using the Goravel ORM. It demonstrates defining a struct to hold the results, executing a `SELECT` query with parameters, and scanning the results into the defined struct. ```go type Result struct { ID int Name string Age int } var result Result facades.Orm().Query().Raw("SELECT id, name, age FROM users WHERE name = ?", "tom").Scan(&result) ``` -------------------------------- ### Sum Aggregation Source: https://www.goravel.dev/orm/getting-started Calculates the sum of a specified column for a given model. ```APIDOC ## SUM AGGREGATION ### Description Calculates the sum of values in a specified column for a given database model. ### Method GET ### Endpoint `/api/orm/sum` ### Parameters #### Query Parameters - **model** (string) - Required - The model to perform the sum on. - **column** (string) - Required - The column to sum. ### Request Example ```json { "model": "models.User", "column": "id" } ``` ### Response #### Success Response (200) - **sum** (integer) - The total sum of the specified column. #### Response Example ```json { "sum": 150 } ``` ``` -------------------------------- ### Exists Source: https://www.goravel.dev/orm/getting-started Checks if records matching the given criteria exist in the database. ```APIDOC ## EXISTS ### Description Checks if records matching the given criteria exist in the database. ### Method GET ### Endpoint `/api/orm/exists` ### Parameters #### Query Parameters - **model** (string) - Required - The model to check for. - **where** (object) - Required - The conditions to match. - **field** (string) - The field name. - **operator** (string) - The comparison operator (e.g., '=', '>', '<'). - **value** (any) - The value to compare against. ### Request Example ```json { "model": "models.User", "where": { "field": "name", "operator": "=", "value": "tom" } } ``` ### Response #### Success Response (200) - **exists** (boolean) - True if records exist, false otherwise. #### Response Example ```json { "exists": true } ``` ``` -------------------------------- ### Register Simple Binding with App Facade in Go Source: https://www.goravel.dev/architecture-concepts/service-container Demonstrates how to register a simple binding using the App facade when outside of a service provider. This allows interaction with the container from any location in the code. ```go facades.App().Bind("key", func(app foundation.Application) (any, error) { ... }) ``` -------------------------------- ### Using Goravel Facades in Go Source: https://www.goravel.dev/architecture-concepts/facades Demonstrates how to import and utilize Goravel's facades to access application functionalities like routing and configuration. This example shows a common pattern for interacting with framework services. ```go import "github.com/goravel/framework/facades" facades.Route().Run(facades.Config().GetString("app.host")) ``` -------------------------------- ### Query Multiple Records Source: https://www.goravel.dev/orm/getting-started Retrieves multiple records based on specified conditions. The `Get` method populates a slice of models with the query results. ```go var users []models.User facades.Orm().Query().Where("id in ?", []int{1,2,3}).Get(&users) ``` -------------------------------- ### Run Goravel Scheduler in main.go Source: https://www.goravel.dev/digging-deeper/task-scheduling This snippet demonstrates how to add the `facades.Schedule().Run()` call to your root `main.go` file to start the Goravel scheduler. It requires bootstrapping the framework first and uses a `select {}` to keep the application running. ```go package main import ( "github.com/goravel/framework/facades" "goravel/bootstrap" ) func main() { // This bootstraps the framework and gets it ready for use. bootstrap.Boot() // Start schedule by facades.Schedule go facades.Schedule().Run() select {} } ``` -------------------------------- ### Scopes API Source: https://www.goravel.dev/orm/getting-started Applies predefined scopes to queries for reusable query logic. ```APIDOC ## SCOPES API ### Description Allows the application of predefined scopes to database queries, enabling reusable query logic. ### Method GET ### Endpoint `/api/orm/query` ### Parameters #### Query Parameters - **scope** (string) - Required - The name of the scope to apply (e.g., 'Paginator'). - **scope_params** (object) - Optional - Parameters for the specified scope. - **page** (string) - The page number. - **limit** (string) - The number of items per page. - **model** (string) - Required - The model to query. ### Request Example ```json { "scope": "Paginator", "scope_params": { "page": "1", "limit": "10" }, "model": "entries" } ``` ### Response #### Success Response (200) - **data** (array) - The query results. #### Response Example ```json { "data": [ { "id": 1, "name": "Example Entry" } ] } ``` ``` -------------------------------- ### Raw Expressions API Source: https://www.goravel.dev/orm/getting-started Allows the use of raw SQL expressions for updating fields. ```APIDOC ## RAW EXPRESSIONS API ### Description Enables the use of raw SQL expressions for updating specific fields in the database. ### Method PUT ### Endpoint `/api/orm/update/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the record to update. #### Request Body - **model** (string) - Required - The model of the record to update. - **field** (string) - Required - The field to update. - **expression** (object) - Required - The raw SQL expression to use for the update. - **sql** (string) - The SQL expression string. - **bindings** (array) - Optional - Values to bind to the SQL expression. ### Request Example ```json { "model": "user", "field": "age", "expression": { "sql": "age - ?", "bindings": [1] } } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example ```json { "message": "Field updated successfully." } ``` ``` -------------------------------- ### Offsetting Query Results Source: https://www.goravel.dev/orm/getting-started Shows how to skip a certain number of records before starting to return results using the Offset method, often used with Limit for pagination. ```APIDOC ## GET /query/offset ### Description Skips a specified number of records before returning results, useful for pagination. ### Method GET ### Endpoint `/query/offset` ### Parameters #### Query Parameters - **name** (string) - Required - The name to filter by. - **offset** (integer) - Required - The number of records to skip. - **limit** (integer) - Required - The maximum number of records to return after skipping. ### Request Example ```go var users []models.User facades.Orm().Query().Where("name = ?", "tom").Offset(5).Limit(3).Get(&users) // SELECT * FROM `users` WHERE name = 'tom' LIMIT 3 OFFSET 5; ``` ### Response #### Success Response (200) - **users** (array[models.User]) - A list of user records, offset and limited as specified. #### Response Example ```json [ { "id": 6, "name": "tom" }, { "id": 7, "name": "tom" }, { "id": 8, "name": "tom" } ] ``` ``` -------------------------------- ### Authorize Actions with Gates in Go Source: https://www.goravel.dev/security/authorization Demonstrates how to authorize actions using the `Allows`, `Denies`, `Any`, and `None` methods of the Gate facade. These methods check if a user has permission for specific abilities. ```go package controllers import ( "github.com/goravel/framework/facades" ) type UserController struct { func (r *UserController) Show(ctx http.Context) http.Response { var post models.Post if facades.Gate().Allows("update-post", map[string]any{ "post": post, }) { } } ``` ```go if facades.Gate().Any([]string{"update-post", "delete-post"}, map[string]any{ "post": post, }) { // The user can update or delete the post... } if facades.Gate().None([]string{"update-post", "delete-post"}, map[string]any{ "post": post, }) { // The user can't update or delete the post... } ``` -------------------------------- ### Build Custom Session with Goravel Facades Source: https://www.goravel.dev/the-basics/session Demonstrates how to construct a custom session instance using the Session facade. It allows specifying a driver and an optional custom session ID. ```go import "github.com/goravel/framework/facades" session := facades.Session().BuildSession(driver, "sessionID") ``` -------------------------------- ### Transaction API Source: https://www.goravel.dev/orm/getting-started Provides functionality to manage database transactions, including automatic and manual control. ```APIDOC ## TRANSACTION API ### Description Manages database transactions, allowing for automatic or manual control of commit and rollback operations. ### Method POST ### Endpoint `/api/orm/transaction` ### Parameters #### Request Body - **operations** (array) - Required - An array of database operations to be executed within the transaction. - Each operation object should contain: - **method** (string) - The HTTP method for the operation (e.g., 'POST', 'PUT', 'DELETE'). - **endpoint** (string) - The API endpoint for the operation. - **body** (object) - Optional - The request body for the operation. ### Request Example ```json { "operations": [ { "method": "POST", "endpoint": "/api/users", "body": { "name": "Goravel" } }, { "method": "PUT", "endpoint": "/api/users/1", "body": { "status": "active" } } ] } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful transaction completion. #### Error Response (400 or 500) - **error** (string) - Description of the transaction failure. #### Response Example ```json { "message": "Transaction committed successfully." } ``` ``` -------------------------------- ### Create and Delete Directories (Go) Source: https://www.goravel.dev/digging-deeper/filesystem Methods for managing directories. `MakeDirectory` creates a directory (and any necessary subdirectories), while `DeleteDirectory` removes a directory and its contents. ```go err := facades.Storage().MakeDirectory(directory) err := facades.Storage().DeleteDirectory(directory) ``` -------------------------------- ### Dispatching Jobs to Default and Specific Queues (Go) Source: https://www.goravel.dev/digging-deeper/queues Demonstrates how to dispatch jobs to the default queue of a connection or to a specific named queue. This is useful for organizing and prioritizing different types of background tasks. ```go // This job is sent to the default connection's default queue err := facades.Queue().Job(&jobs.Test{}, []queue.Arg{ {Type: "int", Value: 1}, }).Dispatch() // This job is sent to the default connection's "emails" queue err := facades.Queue().Job(&jobs.Test{}, []queue.Arg{ {Type: "int", Value: 1}, }).OnQueue("emails").Dispatch() ``` -------------------------------- ### Execute Native Update SQL Source: https://www.goravel.dev/orm/getting-started Executes a native SQL statement and returns the number of affected rows. ```APIDOC ## EXECUTE NATIVE UPDATE SQL ### Description Executes a native SQL statement and returns the number of affected rows. ### Method POST (or other appropriate method for executing arbitrary SQL) ### Endpoint `/api/orm/exec` (example endpoint) ### Parameters #### Request Body - **sql** (string) - Required - The SQL statement to execute. ### Request Example ```json { "sql": "DROP TABLE users" } ``` ### Response #### Success Response (200) - **rows_affected** (integer) - The number of rows affected by the SQL statement. #### Response Example ```json { "rows_affected": 10 } ``` ``` -------------------------------- ### Limiting Query Results Source: https://www.goravel.dev/orm/getting-started Demonstrates how to limit the number of records returned by a query using the Limit method. ```APIDOC ## GET /query/limit ### Description Limits the number of records returned by the query. ### Method GET ### Endpoint `/query/limit` ### Parameters #### Query Parameters - **name** (string) - Required - The name to filter by. - **limit** (integer) - Required - The maximum number of records to return. ### Request Example ```go var users []models.User facades.Orm().Query().Where("name = ?", "tom").Limit(3).Get(&users) // SELECT * FROM `users` WHERE name = 'tom' LIMIT 3; ``` ### Response #### Success Response (200) - **users** (array[models.User]) - A list of user records, limited by the specified number. #### Response Example ```json [ { "id": 1, "name": "tom" }, { "id": 2, "name": "tom" }, { "id": 3, "name": "tom" } ] ``` ``` -------------------------------- ### Dispatching a Job Synchronously (Go) Source: https://www.goravel.dev/digging-deeper/queues Demonstrates how to dispatch a job for immediate, synchronous execution using the `DispatchSync` method. The job runs within the current process, and the program waits for its completion before proceeding. ```go package controllers import ( "github.com/goravel/framework/contracts/queue" "github.com/goravel/framework/contracts/http" "github.com/goravel/framework/facades" "goravel/app/jobs" ) type UserController struct { } func (r *UserController) Show(ctx http.Context) { err := facades.Queue().Job(&jobs.Test{}, []queue.Arg{}).DispatchSync() if err != nil { // do something } } ``` -------------------------------- ### Pessimistic Locking API Source: https://www.goravel.dev/orm/getting-started Provides methods for implementing pessimistic locking (shared lock and lock for update) on select statements. ```APIDOC ## PESSIMISTIC LOCKING API ### Description Implements pessimistic locking mechanisms, including shared locks and 'lock for update' locks, to control concurrent access to database records during transactions. ### Method GET ### Endpoint `/api/orm/lock` ### Parameters #### Query Parameters - **model** (string) - Required - The model to query. - **where** (object) - Required - Conditions for the query. - **field** (string) - The field name. - **operator** (string) - The comparison operator. - **value** (any) - The value to compare. - **lock_type** (string) - Required - The type of pessimistic lock ('shared' or 'for_update'). ### Request Example ```json { "model": "models.User", "where": { "field": "votes", "operator": ">", "value": 100 }, "lock_type": "shared" } ``` ### Response #### Success Response (200) - **data** (array) - The locked records. #### Response Example ```json { "data": [ { "id": 1, "name": "User A" } ] } ``` ``` -------------------------------- ### Prepend String if Not Present (Go) Source: https://www.goravel.dev/digging-deeper/strings The `Start` method ensures a string begins with a specific prefix. If the string does not already start with the prefix, it is added. ```go import "github.com/goravel/framework/support/str" str.Of("framework").Start("/").String() // "/framework" str.Of("/framework").Start("/").String() // "/framework" ``` -------------------------------- ### Not Found Error Handling Source: https://www.goravel.dev/orm/getting-started Explains how to handle cases where a record is not found using FindOrFail, which returns an error if the record does not exist. ```APIDOC ## GET /query/find-or-fail ### Description Retrieves a single record by ID. Returns an error if the record is not found. ### Method GET ### Endpoint `/query/find-or-fail` ### Parameters #### Query Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Request Example ```go var user models.User err := facades.Orm().Query().FindOrFail(&user, 1) // SELECT * FROM `users` WHERE `users`.`id` = 1; // import "github.com/goravel/framework/errors" // if errors.Is(err, errors.OrmRecordNotFound) { // // Handle not found error // } ``` ### Response #### Success Response (200) - **user** (models.User) - The user record found. #### Error Response (404) - **error** (string) - Indicates that the record was not found. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john@example.com" } ``` ``` -------------------------------- ### Starting the Default Queue Worker (Go) Source: https://www.goravel.dev/digging-deeper/queues Provides the basic code to start the Goravel queue worker. This worker will listen for jobs on the default connection and queue as defined in the configuration. ```go package main import ( "github.com/goravel/framework/facades" "goravel/bootstrap" ) func main() { // This bootstraps the framework and gets it ready for use. bootstrap.Boot() // Start queue server by facades.Queue(). go func() { if err := facades.Queue().Worker().Run(); err != nil { facades.Log().Errorf("Queue run error: %v", err) } }() select {} } ``` -------------------------------- ### Offset Query Results Source: https://www.goravel.dev/orm/getting-started Skips a specified number of records before returning results. This is commonly used for pagination, often combined with `Limit`. ```go var users []models.User facades.Orm().Query().Where("name = ?", "tom").Offset(5).Limit(3).Get(&users) ``` -------------------------------- ### Goravel Command Usage Examples Source: https://www.goravel.dev/digging-deeper/artisan-console Provides examples of how to use console commands with options, including short aliases. It also highlights the correct order for defining options and arguments. ```bash go run . artisan emails --lang Chinese go run . artisan emails -l Chinese // Right go run . artisan emails --lang=Chinese name // Wrong go run . artisan emails name --lang=Chinese name ``` -------------------------------- ### Run 'about' Artisan Command (Go) Source: https://www.goravel.dev/upgrade/v1.15 Demonstrates how to use the new `about` Artisan command in Goravel to display framework version and configuration details. This is a convenient way to inspect the application's environment. ```bash go run . artisan about ``` -------------------------------- ### Advanced Querying with Where Clauses Source: https://www.goravel.dev/orm/getting-started Details various 'Where' clause conditions for filtering data, including equality, ranges, null checks, and OR conditions. ```APIDOC ## GET /query/where ### Description Applies various conditions to filter query results. ### Method GET ### Endpoint `/query/where` ### Parameters #### Query Parameters - **name** (string) - Example: 'tom' - **age_min** (integer) - Example: 1 - **age_max** (integer) - Example: 10 - **names_not_in** (array[string]) - Example: ['a'] - **name_null** (boolean) - Example: true - **names_in** (array[string]) - Example: ['a'] ### Request Example ```go // Simple equality facades.Orm().Query().Where("name", "tom") // Raw SQL condition facades.Orm().Query().Where("name = 'tom'") // Parameterized SQL condition facades.Orm().Query().Where("name = ?", "tom") // Between facades.Orm().Query().WhereBetween("age", 1, 10) // Not Between facades.Orm().Query().WhereNotBetween("age", 1, 10) // Not In facades.Orm().Query().WhereNotIn("name", []any{"a"}) // Where Null facades.Orm().Query().WhereNull("name") // Where In facades.Orm().Query().WhereIn("name", []any{"a"}) // Or Where facades.Orm().Query().OrWhere("name = ?", "tom") // Or Where Not In facades.Orm().Query().OrWhereNotIn("name", []any{"a"}) // Or Where Null facades.Orm().Query().OrWhereNull("name") // Or Where In facades.Orm().Query().OrWhereIn("name", []any{"a"}) ``` ### Response #### Success Response (200) - **results** (array) - The filtered records. #### Response Example ```json [ { "id": 1, "name": "tom" } ] ``` ``` -------------------------------- ### Query Single Record Source: https://www.goravel.dev/orm/getting-started Fetches a single model instance from the database. If no record is found, the model remains uninitialized without returning an error. ```go var user models.User facades.Orm().Query().First(&user) ``` -------------------------------- ### Mock Storage Facade for File Operations Source: https://www.goravel.dev/zh/testing/mock Illustrates mocking the Storage facade for testing file operations like putting files. It shows how to mock the context, file creation, and the put file operation, verifying the results. ```go import ( "context" "testing" "github.com/goravel/framework/filesystem" "github.com/goravel/framework/testing/mock" "github.com/goravel/framework/facades" "github.com/stretchr/testify/assert" ) func Storage() (string, error) { file, _ := filesystem.NewFile("1.txt") return facades.Storage().WithContext(context.Background()).PutFile("file", file) } func TestStorage(t *testing.T) { mockFactory := mock.Factory() mockStorage := mockFactory.Storage() mockDriver := mockFactory.StorageDriver() mockStorage.On("WithContext", context.Background()).Return(mockDriver).Once() file, _ := filesystem.NewFile("1.txt") mockDriver.On("PutFile", "file", file).Return("", nil).Once() path, err := Storage() assert.Equal(t, "", path) assert.Nil(t, err) mockStorage.AssertExpectations(t) mockDriver.AssertExpectations(t) } ``` -------------------------------- ### Start gRPC Server in main.go Source: https://www.goravel.dev/the-basics/grpc Starts the gRPC server using the provided configuration. It logs any errors encountered during startup. This function is typically run in a goroutine. ```go go func() { if err := facades.Grpc().Run(facades.Config().GetString("grpc.host")); err != nil { facades.Log().Errorf("Grpc run error: %v", err) } }() ``` -------------------------------- ### Calculate Sum of a Column - Goravel ORM Source: https://www.goravel.dev/orm/getting-started Calculates the sum of values in a specified column for a given model. The result is stored in a provided integer variable. ```go var sum int if err := facades.Orm().Query().Model(models.User{}).Sum("id", &sum); err != nil { return err } fmt.Println(sum) ``` -------------------------------- ### Mock Queue Facade for Job Dispatching Source: https://www.goravel.dev/zh/testing/mock Demonstrates mocking the Queue facade to test job dispatching. It covers setting up a job and its arguments, then verifying that the dispatch method is called correctly. This is essential for testing background task processing. ```go import ( "testing" "github.com/goravel/framework/testing/mock" "github.com/goravel/framework/facades" "github.com/goravel/framework/contracts/queue" "github.com/goravel/framework/jobs" "github.com/stretchr/testify/assert" ) func Queue() error { return facades.Queue().Job(&jobs.TestSyncJob{}, []queue.Arg{}).Dispatch() } func TestQueue(t *testing.T) { mockFactory := mock.Factory() mockQueue := mockFactory.Queue() mockTask := mockFactory.QueueTask() mockQueue.On("Job", mock.Anything, mock.Anything).Return(mockTask).Once() mockTask.On("Dispatch").Return(nil).Once() assert.Nil(t, Queue()) mockQueue.AssertExpectations(t) mockTask.AssertExpectations(t) } ``` -------------------------------- ### Check Record Existence - Goravel ORM Source: https://www.goravel.dev/orm/getting-started Checks if a record exists in the database based on the provided model and conditions. It populates a boolean variable with the result. ```go var exists bool facades.Orm().Query().Model(&models.User{}).Where("name", "tom").Exists(&exists) ``` -------------------------------- ### Define File Serving Routes in Go Source: https://www.goravel.dev/the-basics/routing Configures routes for serving static files using Goravel's routing facade. facades.Route().Static() serves files from a directory, facades.Route().StaticFile() serves a single file, and facades.Route().StaticFS() serves files from an http.FileSystem. ```go import "net/http" facades.Route().Static("static", "./public") facades.Route().StaticFile("static-file", "./public/logo.png") facades.Route().StaticFS("static-fs", http.Dir("./public")) ``` -------------------------------- ### Retrieve Environment Configuration in Go Source: https://www.goravel.dev/getting-started/configuration This snippet shows how to retrieve configuration values from the .env file using the facades.Config().Env() method. The first parameter is the configuration key, and the second is an optional default value. ```go // The first parameter is the configuration key, and the second parameter is the default value facades.Config().Env("APP_NAME", "goravel") ``` -------------------------------- ### Query Record by ID Source: https://www.goravel.dev/orm/getting-started Retrieves a single record by its primary key or multiple records by a slice of primary keys. This method is efficient for direct lookups. ```go var user models.User facades.Orm().Query().Find(&user, 1) var users []models.User facades.Orm().Query().Find(&users, []int{1,2,3}) ``` -------------------------------- ### Set Configuration Values in Go Source: https://www.goravel.dev/getting-started/configuration This code illustrates how to add or update configuration values dynamically using the facades.Config().Add() method. It supports setting simple key-value pairs, nested values using dot notation, and complex types like maps. ```go facades.Config().Add("path", "value1") facades.Config().Add("path.with.dot.case1", "value1") facades.Config().Add("path.with.dot", map[string]any{"case3": "value3"}) ``` -------------------------------- ### Restore Soft-Deleted Records - Goravel ORM Source: https://www.goravel.dev/orm/getting-started Restores soft-deleted records. This can be done by specifying the model instance with an ID or by using the model and ID directly in the query. ```go facades.Orm().Query().WithTrashed().Restore(&models.User{ID: 1}) facades.Orm().Query().Model(&models.User{ID: 1}).WithTrashed().Restore() // UPDATE `users` SET `deleted_at`=NULL WHERE `id` = 1; ``` -------------------------------- ### Registering Jobs in QueueServiceProvider (Go) Source: https://www.goravel.dev/digging-deeper/queues Illustrates how to register custom job classes within the `QueueServiceProvider` to make them available for the queue system. This ensures that the framework can correctly instantiate and process these jobs. ```go func (receiver *QueueServiceProvider) Jobs() []queue.Job { return []queue.Job{ &jobs.Test{}, } } ``` -------------------------------- ### Custom Primary Key Query Source: https://www.goravel.dev/orm/getting-started Illustrates how to query records when the primary key is not of the default type (e.g., string UUID) by specifying the primary key column. ```APIDOC ## GET /query/custom-pk ### Description Retrieves a record using a custom primary key column when the primary key is not of the default type. ### Method GET ### Endpoint `/query/custom-pk` ### Parameters #### Query Parameters - **uuid** (string) - Required - The UUID of the user to retrieve. ### Request Example ```go var user models.User facades.Orm().Query().Find(&user, "uuid=?", "a") // SELECT * FROM `users` WHERE `users`.`uuid` = "a"; ``` ### Response #### Success Response (200) - **user** (models.User) - The user record found. #### Response Example ```json { "id": 1, "uuid": "a", "name": "John Doe" } ``` ``` -------------------------------- ### Query Record with String Primary Key Source: https://www.goravel.dev/orm/getting-started Finds a record when the primary key is of string type. Requires specifying the primary key column and its value in the query. ```go var user models.User facades.Orm().Query().Find(&user, "uuid=?" ,"a") ``` -------------------------------- ### Query Record by ID or Fail Source: https://www.goravel.dev/orm/getting-started Attempts to retrieve a single record by its primary key. If the record is not found, it returns an error, allowing for explicit error handling. ```go var user models.User err := facades.Orm().Query().FindOrFail(&user, 1) ``` -------------------------------- ### Get Project Information using Artisan CLI Source: https://www.goravel.dev/getting-started/configuration This command-line instruction shows how to use the Goravel artisan tool to display project information, including framework version and configuration details. ```bash go run . artisan about ``` -------------------------------- ### Publish Package Configuration with Goravel Service Provider Source: https://www.goravel.dev/digging-deeper/package-development This Go code snippet demonstrates how to publish a package's configuration file to the application's config directory using the `Publishes` method within a Goravel service provider's `Boot` method. It maps the package's configuration file to the application's config path. ```go func (receiver *ServiceProvider) Boot(app foundation.Application) { app.Publishes("github.com/goravel/example-package", map[string]string{ "config/sms.go": app.ConfigPath("sms.go"), }) } ``` -------------------------------- ### Muting All Events Source: https://www.goravel.dev/orm/getting-started Temporarily mute all events fired by a model using the `WithoutEvents` method. This is useful when you want to perform operations without triggering any model event listeners. ```APIDOC ## Muting All Events ### Description Temporarily mute all events fired by a model using the `WithoutEvents` method. ### Method GET (Implicitly used within the ORM query) ### Endpoint N/A (Internal ORM method) ### Parameters None ### Request Example ```go var user models.User facades.Orm().Query().WithoutEvents().Find(&user, 1) ``` ### Response #### Success Response (200) N/A (Operation modifies internal state or fetches data) #### Response Example N/A ``` -------------------------------- ### Querying Single Records Source: https://www.goravel.dev/orm/getting-started Demonstrates how to retrieve a single record from the database using First and FirstOr methods. FirstOr allows specifying a closure to execute if no record is found. ```APIDOC ## GET /query/first ### Description Retrieves the first record matching the query criteria or executes a closure if no record is found. ### Method GET ### Endpoint `/query/first` ### Parameters None ### Request Example ```go var user models.User facades.Orm().Query().First(&user) // SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1; facades.Orm().Query().Where("name", "first_user").FirstOr(&user, func() error { user.Name = "goravel" return nil }) ``` ### Response #### Success Response (200) - **user** (models.User) - The first user record found or a user instance populated by the closure. #### Response Example ```json { "id": 1, "name": "goravel", "email": "example@example.com" } ``` ```