### Create a New LaraGram Application Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md This command initiates the creation of a new LaraGram application named 'example-app'. The installer will guide you through database selection and bot configuration. ```shell laragram new example-app ``` -------------------------------- ### Start LaraGram API Server Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md Command to start a LaraGram API server. Requires setting `api_id` and `api_hash` in the configuration. ```shell php laragram start:apiserver ``` -------------------------------- ### Start LaraGram Local Development Server Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md After creating a LaraGram application, navigate into the application directory and use this command to start the local development server. The application will be accessible at http://localhost:9000 for webhook setup. ```shell cd example-app php laragram serve ``` -------------------------------- ### Install and Run LaraGram Application Source: https://context7.com/laraxgram/laraxgram.github.io/llms.txt Commands to install the LaraGram installer, create a new application, start the development server, set up webhooks, and run database migrations. ```shell # Install the LaraGram installer globally composer global require laraxgram/installer # Create a new application laragram new example-app # Start the development server cd example-app php laragram serve # Set up webhook for your bot php laragram webhook:set # Run database migrations php laragram migrate ``` -------------------------------- ### Build Eloquent Queries with Constraints Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Demonstrates how to build Eloquent queries by chaining methods like `where`, `orderBy`, and `limit` before retrieving results with `get`. This allows for flexible data retrieval based on specific criteria. ```php $flights = Flight::where('active', 1) ->orderBy('name') ->limit(10) ->get(); ``` -------------------------------- ### Install LaraGram Installer via Composer Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md If PHP and Composer are already installed, this command installs the LaraGram installer globally using Composer. This is an alternative to the script-based installation. ```shell composer global require laraxgram/installer ``` -------------------------------- ### Example SQL query with global scope applied Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This SQL query demonstrates the effect of applying a global scope. The `where` clause from the scope is automatically included in the generated SQL. ```sql select * from `users` where `created_at` < 0021-02-18 00:00:00 ``` -------------------------------- ### Configure MySQL Database Connection Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md Example of how to configure a MySQL database connection in the `.env` file for LaraGram. This involves updating `DB_*` variables. ```ini DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laragram DB_USERNAME=root DB_PASSWORD= ``` -------------------------------- ### Utilize Chained Local Eloquent Scopes in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Demonstrates how to apply defined local scopes to Eloquent queries. Scopes can be chained together, and 'orWhere' can be used with closures or LaraGram's higher-order 'orWhere' for complex conditions. This example retrieves popular and active users. ```php use App\Models\User; $users = User::popular()->active()->orderBy('created_at')->get(); ``` ```php $users = User::popular()->orWhere(function (Builder $query) { $query->active(); })->get(); ``` ```php $users = User::popular()->orWhere->active()->get(); ``` -------------------------------- ### PHPDoc Example: Native Type Hinting Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/contributions.md Illustrates PHPDoc usage when native type hints are sufficient, such as for a 'handle' method with a void return type. Redundant `@param` and `@return` tags can be omitted. ```php /** * Execute the job. */ public function handle(AudioProcessor $processor): void { // } ``` -------------------------------- ### Install PHP, Composer, and LaraGram Installer (Windows PowerShell) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md This command installs PHP version 8.4, Composer, and the LaraGram installer on Windows using PowerShell. It requires administrator privileges and sets the security protocol for downloading. Restart your terminal after execution. ```powershell # Run as administrator... Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4')) ``` -------------------------------- ### Retrieve or Create Eloquent Models Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Explains the firstOrCreate and firstOrNew methods for retrieving models. firstOrCreate will create a new record if none exists, while firstOrNew will return a new, unsaved model instance. ```php use App\Models\Flight; // Retrieve flight by name or create it if it doesn't exist... $flight = Flight::firstOrCreate([ 'name' => 'London to Paris' ]); // Retrieve flight by name or create it with the name, delayed, and arrival_time attributes... $flight = Flight::firstOrCreate( ['name' => 'London to Paris'], ['delayed' => 1, 'arrival_time' => '11:30'] ); // Retrieve flight by name or instantiate a new Flight instance... $flight = Flight::firstOrNew([ 'name' => 'London to Paris' ]); // Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes... $flight = Flight::firstOrNew( ['name' => 'Tokyo to Sydney'], ['delayed' => 1, 'arrival_time' => '11:30'] ); ``` -------------------------------- ### Create User Observer with Artisan Command Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This command generates a new observer class for the User model. It places the observer in the app/Observers directory, creating it if it doesn't exist. This is the primary way to scaffold an observer. ```shell php laragram make:observer UserObserver --model=User ``` -------------------------------- ### Restore Soft Deleted Models in Relationship Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This example shows how to restore soft-deleted models within an Eloquent relationship. The `restore()` method can be called on the relationship query. ```php $flight->history()->restore(); ``` -------------------------------- ### Start Asynchronous Process (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/processes.md Demonstrates how to start a process asynchronously using the `start()` method, allowing the application to continue execution while the process runs in the background. The `running()` method can check if the process is still active. ```php $process = Process::timeout(120)->start('bash import.sh'); while ($process->running()) { // ... } $result = $process->wait(); ``` -------------------------------- ### Include Soft Deleted Models in Query Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This example shows how to include soft-deleted models in query results by using the `withTrashed()` method. By default, soft-deleted models are excluded from queries. ```php use App\Models\Flight; $flights = Flight::withTrashed() ->where('account_id', 1) ->get(); ``` -------------------------------- ### Basic Controller Example in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/controllers.md An example of a basic controller class with a `show` method. This method handles a specific bot request, retrieves user data, and renders a profile template. It depends on the `App\Models\User` model. ```php User::findOrFail($id) ]); } } ``` -------------------------------- ### Register Service with Configuration Repository (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/surge.md Demonstrates registering a service with its constructor receiving the configuration repository. This approach can lead to stale configuration data if the service is a singleton and configurations change between requests. ```php use App\Service; use LaraGram\Contracts\Foundation\Application; /** * Register any application services. */ public function register(): void { $this->app->singleton(Service::class, function (Application $app) { return new Service($app->make('config')); }); } ``` -------------------------------- ### Set Keyboard Options (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/keyboards.md Provides examples of how to set options for the keyboard, such as `resize_keyboard` and `one_time_keyboard`. Options can be set individually or as an array. ```php $keyboard->setOption('resize_keyboard', false); // Or $keyboard->setOptions([ 'resize_keyboard' => false, 'one_time_keyboard' => true ]); ``` -------------------------------- ### Restore a Soft Deleted Model Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This example shows how to restore a soft-deleted model by calling the `restore()` method. This action sets the `deleted_at` column back to `null`, making the model visible in regular queries again. ```php $flight->restore(); ``` -------------------------------- ### Utilize Dynamic Eloquent Scope with Arguments in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Illustrates calling a dynamic scope with the required arguments. The arguments are passed directly when invoking the scope method on the model query. This example retrieves users of the 'admin' type. ```php $users = User::ofType('admin')->get(); ``` -------------------------------- ### Retrieve Policy Instance with policy() Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/helpers.md The `policy` method retrieves a policy instance for a given class. It takes the class name as a string argument. ```php $policy = policy(App\Models\User::class); ``` -------------------------------- ### Subquery Ordering for Sorting in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md The `orderBy` function in Eloquent's query builder supports subqueries for dynamic sorting. This example sorts destinations based on the arrival time of their last flight, all within a single database query. ```php return Destination::orderByDesc( Flight::select('arrived_at') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1) )->get(); ``` -------------------------------- ### Build Log Stacks Configuration Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/logging.md The 'stack' driver allows combining multiple log channels into one. This example configures a 'stack' channel that aggregates 'syslog' and 'slack' channels. It also shows configurations for 'syslog' and 'slack' channels. ```php 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['syslog', 'slack'], 'ignore_exceptions' => false, ], 'syslog' => [ 'driver' => 'syslog', 'level' => env('LOG_LEVEL', 'debug'), 'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER), 'replace_placeholders' => true, ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => env('LOG_SLACK_USERNAME', 'LaraGram Log'), 'emoji' => env('LOG_SLACK_EMOJI', ':boom:'), 'level' => env('LOG_LEVEL', 'critical'), 'replace_placeholders' => true, ], ], ``` -------------------------------- ### Filtering Cursor Results with Lazy Collections in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Results from the `cursor` method return a `LazyCollection`, enabling the use of collection methods while maintaining low memory usage. This example filters users by ID greater than 500 before iterating. ```php use App\Models\User; $users = User::cursor()->filter(function (User $user) { return $user->id > 500; }); foreach ($users as $user) { echo $user->id; } ``` -------------------------------- ### Define Global Listen Parameter Constraints in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Explains how to define global regular expression patterns for listen parameters in the `boot` method of `AppProvidersAppServiceProvider`. These global patterns are automatically applied to all listens using the specified parameter name. ```php use LaraGram\Support\Facades\Bot; /** * Bootstrap any application services. */ public function boot(): void { Bot::pattern('id', '[0-9]+'); } ``` ```php Bot::onText('user {id}', function (string $id) { // Only executed if {id} is numeric... }); ``` -------------------------------- ### Registering Multiple Bindings and Singletons in a Provider Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/providers.md This example shows how to register multiple container bindings and singletons using the `$bindings` and `$singletons` properties within a service provider. The framework automatically registers these when the provider is loaded. ```php DigitalOceanServerProvider::class, ]; /** * All of the container singletons that should be registered. * * @var array */ public $singletons = [ DowntimeNotifier::class => PingdomDowntimeNotifier::class, ServerProvider::class => ServerToolsProvider::class, ]; } ``` -------------------------------- ### Define Eloquent Scope with Pending Attributes in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Demonstrates using `withAttributes` within a scope to set model attributes for both query conditions and newly created models. This example defines a 'draft' scope that sets the 'hidden' attribute to true. ```php withAttributes([ 'hidden' => true, ]); } } ``` -------------------------------- ### Dependency Injection in PodcastController (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/container.md Demonstrates how to inject the AppleMusic service into a PodcastController using constructor property promotion. This allows for easy mocking of the service during testing. ```php $this->apple->findPodcast($id) ]); } } ``` -------------------------------- ### Define Dynamic Eloquent Scope with Parameters in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Shows how to create a local scope that accepts parameters. Additional parameters are added to the scope method signature after the `$query` parameter. This example defines a scope to filter users by a given type. ```php where('type', $type); } } ``` -------------------------------- ### Subquery Selects for Related Data in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Eloquent's query builder allows advanced subquery selects to retrieve data from related tables in a single query. This example selects destinations and the name of the most recently arrived flight for each destination. ```php use App\Models\Destination; use App\Models\Flight; return Destination::addSelect(['last_flight' => Flight::select('name') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1) ])->get(); ``` -------------------------------- ### Podcast Model With Real-Time Facade (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/facades.md This PHP code demonstrates refactoring the `Podcast` model to use a real-time facade for the `Publisher`. The `Publisher` is now resolved from the service container, eliminating the need for explicit injection and simplifying method calls. ```php update(['publishing' => now()]); // $publisher->publish($this); // [!code --] Publisher::publish($this); // [!code ++] } } ``` -------------------------------- ### Install PHP, Composer, and LaraGram Installer (Linux) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md This command installs PHP version 8.4, Composer, and the LaraGram installer on Linux using a bash script. Ensure you restart your terminal after execution. ```shell /bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)" ``` -------------------------------- ### Inspect Database Schema Overview using Shell Command Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/database.md The `db:show` command provides an overview of your database, including its size, type, and a summary of its tables. You can also inspect specific connections and include table row counts or view details. ```shell php laragram db:show php laragram db:show --database=pgsql php laragram db:show --counts --views ``` -------------------------------- ### Install PHP, Composer, and LaraGram Installer (macOS) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md This command installs PHP version 8.4, Composer, and the LaraGram installer on macOS using a bash script. Ensure you restart your terminal after execution. ```shell /bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)" ``` -------------------------------- ### Generate Pattern and Redirects with Named Listens (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Demonstrates how to use the `listen` and `redirect` helper functions with named listens to generate patterns and redirects. It also shows how to pass parameters for listens that define them. ```php // Generating Pattern... $pattern = listen('profile'); // Generating Redirects... return redirect()->listen('profile'); return to_listen('profile'); ``` ```php Bot::onText('user {id}', function ($id) { // ... })->name('user'); $pattern = listen('user', ['id' => 1]); ``` -------------------------------- ### Utilize Eloquent Scope with Pending Attributes for Model Creation in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Shows how to create a model using a scope that includes pending attributes. The `withAttributes` method adds `where` conditions and sets attributes on the created model. This example creates a draft post. ```php $draft = Post::draft()->create(['title' => 'In Progress']); $draft->hidden; // true ``` ```php $query->withAttributes([ 'hidden' => true, ], asConditions: false); ``` -------------------------------- ### Testing Helper Functions with Cache Example in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/facades.md Shows how to test a helper function, specifically the 'cache' helper, by asserting that the underlying facade's method was called. This illustrates that helper functions can be tested like their facade counterparts. ```php Bot::onText('cache', function () { $data = cache('key'); }); ``` -------------------------------- ### Create and Render a Basic Template in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/templates.md Demonstrates how to define a simple template file and then render it from a PHP controller using the global `template` helper function. This separates presentation logic from controller logic. ```blade @text() Hello, {{ $name }} @endText ``` ```php Bot::onText('hi', function () { return template('greeting', ['name' => 'James']); }); ``` -------------------------------- ### Get or Set Configuration Values Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/helpers.md The `config` function retrieves configuration values using dot notation or sets them at runtime for the current request. It can also accept a default value. ```php $value = config('app.timezone'); $value = config('app.timezone', $default); config(['app.debug' => true]); ``` -------------------------------- ### Retrieve Eloquent Models or Execute Closure Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Shows how to use findOr and firstOr methods to retrieve a single Eloquent model or execute a closure if no matching record is found. The return value of the closure becomes the method's result. ```php $flight = Flight::findOr(1, function () { // ... }); $flight = Flight::where('legs', '>', 3)->firstOr(function () { // ... }); ``` -------------------------------- ### Register Queueable Anonymous Event Listeners (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This example illustrates how to register queueable anonymous event listeners for Eloquent model events. By wrapping the closure with `queueable()`, the event listener will be executed in the background via LaraGram's queue system, improving application responsiveness. ```php use function LaraGram\Events\queueable; static::created(queueable(function (User $user) { // ... })); ``` -------------------------------- ### Example Template Composer Class Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/templates.md This PHP class serves as an example of a template composer. It demonstrates how to inject dependencies, such as `UserRepository`, via the constructor and how to use the `compose` method to bind data to a template. The `compose` method receives a `Template` instance and uses its `with` method to pass data. ```php with('count', $this->users->count()); } } ``` -------------------------------- ### Define Local Eloquent Scopes in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Defines common query constraints as local scopes within an Eloquent model. Scopes are defined using the `#[Scope]` attribute and must return a query builder instance or void. This example shows scopes for 'popular' and 'active' users. ```php where('votes', '>', 100); } /** * Scope a query to only include active users. */ #[Scope] protected function active(Builder $query): void { $query->where('active', 1); } } ``` -------------------------------- ### Getting Morph Alias and Model Class in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent-relationships.md Provides examples of how to get the morph alias of a model instance using `getMorphClass` and how to resolve the fully-qualified class name from a morph alias using `Relation::getMorphedModel` in PHP. ```php use LaraGram\Database\Eloquent\Relations\Relation; $alias = $post->getMorphClass(); $class = Relation::getMorphedModel($alias); ``` -------------------------------- ### Retrieve View Instance (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/helpers.md The `template` function is used to retrieve a view instance. It takes a string representing the view path as its argument. ```php return template('panel.admin'); ``` -------------------------------- ### Get Substring from String - PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/strings.md The `substr` method extracts a portion of a string based on a starting position and an optional length. If the length is omitted, it returns the rest of the string from the start position. This method is part of the LaraGram Str helper class. ```php use LaraGram\Support\Str; $string = Str::of('LaraGram Framework')->substr(8); // Framework $string = Str::of('LaraGram Framework')->substr(8, 5); // Frame ``` -------------------------------- ### Create On-Demand Log Channel in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/logging.md Demonstrates how to create a log channel dynamically at runtime using the Log facade's build method. This is useful when a channel configuration is not present in the application's logging configuration file. It takes a configuration array specifying the driver and path. ```php use LaraGram\Support\Facades\Log; Log::build([ 'driver' => 'single', 'path' => storage_path('logs/custom.log'), ])->info('Something happened!'); ``` -------------------------------- ### Apply Prefix to Listen Patterns in Groups (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Shows how to use the `prefix` method to add a common pattern prefix to all listens within a group, ensuring they all start with the specified string. ```php Bot::prefix('set')->group(function () { Bot::onText('admin', function () { // Matches The "set admin" text messages }); }); ``` -------------------------------- ### Run LaraGram Database Migrations Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md Command to run database migrations for a LaraGram application. This is necessary when using a database other than SQLite. ```shell php laragram migrate ``` -------------------------------- ### Set LaraGram Webhook Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/installation.md Command to set the webhook for a LaraGram bot connection. Requires defining bot connections in `config/bot.php`. ```shell php laragram webhook:set ``` -------------------------------- ### Retrieve Original and Changed Eloquent Model Attributes (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Shows how to use `getOriginal` to retrieve the initial attribute values and `getChanges` and `getPrevious` to get the attributes that were modified during the last save operation. These methods are useful for auditing and debugging. ```php $user = User::find(1); $user->name; // John $user->email; // john@example.com $user->name = 'Jack'; $user->name; // Jack $user->getOriginal('name'); // John $user->getOriginal(); // Array of original attributes... $user->update([ 'name' => 'Jack', 'email' => 'jack@example.com', ]); $user->getChanges(); /* [ 'name' => 'Jack', 'email' => 'jack@example.com', ] */ $user->getPrevious(); /* [ 'name' => 'John', 'email' => 'john@example.com', ] */ ``` -------------------------------- ### Real-time Output with Closures Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/processes.md Shows how to capture output from an asynchronous process in real-time as it's generated. A closure is provided to the `start` method, receiving the output type and the output string. ```php $process = Process::start('bash import.sh', function (string $type, string $output) { echo $output; }); $result = $process->wait(); ``` -------------------------------- ### Take Characters from Start of String - PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/strings.md The `take` method extracts a specified number of characters from the beginning of a string. This is useful for getting prefixes or truncating strings from the left. ```php use LaraGram\Support\Str; $taken = Str::of('Build something amazing!')->take(5); // Build ``` -------------------------------- ### Create Process Pipelines with Command Array (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/processes.md Demonstrates a simpler way to create process pipelines by passing an array of command strings directly to the `pipe()` method. This is suitable when individual process customization is not required. ```php $result = Process::pipe([ 'cat example.txt', 'grep -i "laragram"', ]); ``` -------------------------------- ### Delete a Model Instance in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md To delete a specific model instance, retrieve it from the database and then call the `delete` method on the model object. ```php use App\Models\Flight; $flight = Flight::find(1); $flight->delete(); ``` -------------------------------- ### Name Bot Listens in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Demonstrates how to assign a unique name to a bot listen using the `name` method. This is useful for generating redirects to specific listens. The example shows naming a command listen and a listen mapped to a controller action. ```php Bot::onCommand('panel', function () { // ... })->name('profile'); ``` ```php Bot::onCommand( 'panel', [UserProfileController::class, 'show'] )->name('profile'); ``` -------------------------------- ### PHPDoc Example: Binding Registration Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/contributions.md Demonstrates a valid LaraGram documentation block for registering a binding with the container. It specifies parameter types, return type, and potential exceptions. ```php /** * Register a binding with the container. * * @param string|array $abstract * @param \Closure|string|null $concrete * @param bool $shared * @return void * * @throws \Exception */ public function bind($abstract, $concrete = null, $shared = false) { // ... } ``` -------------------------------- ### Retrieve Only Soft Deleted Models Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This code shows how to retrieve only the soft-deleted models from the database using the `onlyTrashed()` method. This is useful for displaying or managing records that have been marked as deleted. ```php $flights = Flight::onlyTrashed() ->where('airline_id', 1) ->get(); ``` -------------------------------- ### Use Regex Constraint Helper Methods in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Provides examples of using convenient helper methods like `whereNumber`, `whereAlpha`, `whereAlphaNumeric`, `whereUuid`, `whereUlid`, and `whereIn` to apply common regular expression constraints to listen parameters. ```php Bot::onText('user {id} {name}', function (string $id, string $name) { // ... })->whereNumber('id')->whereAlpha('name'); ``` ```php Bot::onText('user {name}', function (string $name) { // ... })->whereAlphaNumeric('name'); ``` ```php Bot::onText('user {id}', function (string $id) { // ... })->whereUuid('id'); ``` ```php Bot::onText('user {id}', function (string $id) { // ... })->whereUlid('id'); ``` ```php Bot::onText('category {slug}', function (string $id) { // ... })->whereIn('slug', ['movie', 'song', 'painting']); ``` ```php Bot::onText('category {slug}', function (string $category) { // ... })->whereIn('slug', CategoryEnum::cases()); ``` -------------------------------- ### List All Application Listeners with `listen:list` (Shell) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md The `listen:list` Artisan command provides an overview of all defined listeners in your application. You can use options like `-v` to show middleware, `--pattern` to filter by pattern, `--except-vendor` to exclude vendor listeners, and `--only-vendor` to include only vendor listeners. ```shell php laragram listen:list php laragram listen:list -v php laragram listen:list -vv php laragram listen:list --pattern=admin php laragram listen:list --except-vendor php laragram listen:list --only-vendor ``` -------------------------------- ### Include Soft Deleted Models in Relationship Query Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This snippet demonstrates how to include soft-deleted models when querying an Eloquent relationship. The `withTrashed()` method is applied to the relationship query. ```php $flight->history()->withTrashed()->get(); ``` -------------------------------- ### Registering Multiple Bot Verbs with 'match' in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Demonstrates how to register a single listener that responds to multiple bot verbs using the 'match' method. This is useful for consolidating logic that should be triggered by various types of incoming messages or commands. ```php Bot::match(['TEXT', 'COMMAND'], 'start', function () { // ... }); ``` -------------------------------- ### Permanently Delete Soft Deleted Models in Relationship Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md This snippet demonstrates how to permanently delete soft-deleted models associated with a relationship. The `forceDelete()` method is called on the relationship query. ```php $flight->history()->forceDelete(); ``` -------------------------------- ### Chunk Results with Grouped Conditions Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Shows how to use `chunkById` with logically grouped conditions for complex filtering scenarios. This is necessary because `chunkById` adds its own 'where' conditions to the query. ```php Flight::where(function ($query) { $query->where('delayed', true)->orWhere('cancelled', true); })->chunkById(200, function (Collection $flights) { $flights->each->update([ 'departed' => false, 'cancelled' => true ]); }, column: 'id'); ``` -------------------------------- ### Apply Name Prefix to Listen Names in Groups (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Explains how to use the `name` method to prefix the names of all listens within a group with a given string, including the necessary trailing character for correct concatenation. ```php Bot::name('admin.')->group(function () { Bot::onText('users', function () { // Listen assigned name "admin.users"... })->name('users'); }); ``` -------------------------------- ### Replicate Model Instance Excluding Attributes (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md When replicating a model, you can exclude specific attributes from being copied to the new instance by passing an array of attribute names to the `replicate` method. ```php use App\Models\Flight; $flight = Flight::create([ 'destination' => 'LAX', 'origin' => 'LHR', 'last_flown' => '2020-03-04 11:00:00', 'last_pilot_id' => 747, ]); $flight = $flight->replicate([ 'last_flown', 'last_pilot_id' ]); ``` -------------------------------- ### Access Current Listen Information via Bot Facade Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Demonstrates how to retrieve details about the currently active listen using the `Listen` facade. It provides methods to get the listen object, its name, and its action. ```php use LaraGram\Support\Facades\Bot; $listen = Bot::current(); // LaraGram\Listening\Listen $name = Bot::currentListenName(); // string $action = Bot::currentListenAction(); // string ``` -------------------------------- ### Schedule Model Pruning Command (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Schedule the `model:prune` Artisan command in your `app/Console/Kernel.php` or `listens/console.php` file. You can specify models to prune, exclude, or run in pretend mode. ```php use LaraGram\Support\Facades\Schedule; Schedule::command('model:prune')->daily(); Schedule::command('model:prune', [ '--model' => [Address::class, Flight::class], ])->daily(); Schedule::command('model:prune', [ '--except' => [Address::class, Flight::class], ])->daily(); ``` -------------------------------- ### Publishing Configuration Files in Shell Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/configuration.md Demonstrates how to publish configuration files that are not included by default using the config:publish Commander command. The --all flag publishes all configuration files. ```shell php laragram config:publish php laragram config:publish --all ``` -------------------------------- ### Apply Middleware to Listen Groups (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/listening.md Illustrates how to assign middleware to all listens within a group using the `middleware` method before defining the group. Middleware are executed in the order they are provided. ```php Bot::middleware(['first', 'second'])->group(function () { Bot::onText('hello', function () { // Uses first & second middleware... }); Bot::onText('bye', function () { // Uses first & second middleware... }); }); ``` -------------------------------- ### Retrieve All Eloquent Models Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Fetch all records from a model's associated database table using the `all()` method. This method returns a collection of model instances, allowing you to iterate over the results. ```php use App\Models\Flight; foreach (Flight::all() as $flight) { echo $flight->name; } ``` -------------------------------- ### PHPDoc Example: Generic Native Types Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/contributions.md Shows how to use `@param` or `@return` attributes to specify generic native types when the native type hint itself is generic, like for an array of specific objects. ```php /** * Get the attachments for the message. * * @return array */ public function attachments(): array { return [ Attachment::fromStorage('/path/to/file'), ]; } ``` -------------------------------- ### Create Basic Redirect Response with Helper Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/redirects.md Demonstrates the simplest way to create a redirect response using the global `redirect` helper function. This is useful for redirecting users to a specific listen after a command. ```php Bot:onCommand('dashboard', function () { return redirect()->listen('home'); }); ``` -------------------------------- ### Using Cache Facade in a Controller in PHP Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/facades.md Illustrates the practical application of the Cache facade within a LaraGram controller to retrieve user data. It shows how to import the facade and use its static methods to interact with the caching system. ```php $user]); } } ``` -------------------------------- ### N+1 Query Problem Example - SQL Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent-relationships.md Illustrates the N+1 query problem where fetching all books and then iterating to get each author's name results in one query for books and N additional queries for authors. ```sql select * from books select * from authors where id in (1, 2, 3, 4, 5, ...) ``` -------------------------------- ### Registering an Immediate Tick Operation (PHP) Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/surge.md Shows how to configure a tick operation to execute immediately upon Surge server boot and then at the specified interval thereafter, using the `immediate` method. ```php Surge::tick('simple-ticker', fn () => ray('Ticking...')) ->seconds(10) ->immediate(); ``` -------------------------------- ### Apply global scope using attribute Source: https://github.com/laraxgram/laraxgram.github.io/blob/master/src/v3/eloquent.md Assign a global scope to a model by using the `ScopedBy` attribute on the model class. This attribute takes an array of scope class names to be applied. ```php as('first')->command('bash import-1.sh'); $pool->as('second')->command('bash import-2.sh'); $pool->as('third')->command('bash import-3.sh'); })->start(function (string $type, string $output, string $key) { // ... }); $results = $pool->wait(); return $results['first']->output(); ```