├── artisan.md
├── authentication.md
├── authorization.md
├── billing.md
├── blade.md
├── broadcasting.md
├── cache.md
├── cashier-paddle.md
├── collections.md
├── configuration.md
├── console-tests.md
├── container.md
├── contracts.md
├── contributions.md
├── controllers.md
├── csrf.md
├── database-testing.md
├── database.md
├── deployment.md
├── dictionary.md
├── documentation.md
├── dusk.md
├── eloquent-collections.md
├── eloquent-mutators.md
├── eloquent-relationships.md
├── eloquent-resources.md
├── eloquent-serialization.md
├── eloquent.md
├── encryption.md
├── envoy.md
├── errors.md
├── events.md
├── facades.md
├── filesystem.md
├── fortify.md
├── hashing.md
├── helpers.md
├── homestead.md
├── horizon.md
├── http-client.md
├── http-tests.md
├── installation.md
├── license.md
├── lifecycle.md
├── localization.md
├── logging.md
├── mail.md
├── middleware.md
├── migrations.md
├── mix.md
├── mocking.md
├── notifications.md
├── octane.md
├── packages.md
├── pagination.md
├── passport.md
├── passwords.md
├── providers.md
├── queries.md
├── queues.md
├── rate-limiting.md
├── readme.md
├── redirects.md
├── redis.md
├── releases.md
├── requests.md
├── responses.md
├── routing.md
├── sail.md
├── sanctum.md
├── scheduling.md
├── scout.md
├── seeding.md
├── session.md
├── socialite.md
├── starter-kits.md
├── structure.md
├── telescope.md
├── testing.md
├── upgrade.md
├── urls.md
├── valet.md
├── validation.md
├── verification.md
└── views.md
/configuration.md:
--------------------------------------------------------------------------------
1 | # Configuration
2 |
3 | - [Introduction](#introduction)
4 | - [Environment Configuration](#environment-configuration)
5 | - [Environment Variable Types](#environment-variable-types)
6 | - [Retrieving Environment Configuration](#retrieving-environment-configuration)
7 | - [Determining The Current Environment](#determining-the-current-environment)
8 | - [Accessing Configuration Values](#accessing-configuration-values)
9 | - [Configuration Caching](#configuration-caching)
10 | - [Debug Mode](#debug-mode)
11 | - [Maintenance Mode](#maintenance-mode)
12 |
13 |
14 | ## Introduction
15 |
16 | All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
17 |
18 | These configuration files allow you to configure things like your database connection information, your mail server information, as well as various other core configuration values such as your application timezone and encryption key.
19 |
20 |
21 | ## Environment Configuration
22 |
23 | It is often helpful to have different configuration values based on the environment where the application is running. For example, you may wish to use a different cache driver locally than you do on your production server.
24 |
25 | To make this a cinch, Laravel utilizes the [DotEnv](https://github.com/vlucas/phpdotenv) PHP library. In a fresh Laravel installation, the root directory of your application will contain a `.env.example` file that defines many common environment variables. During the Laravel installation process, this file will automatically be copied to `.env`.
26 |
27 | Laravel's default `.env` file contains some common configuration values that may differ based on whether your application is running locally or on a production web server. These values are then retrieved from various Laravel configuration files within the `config` directory using Laravel's `env` function.
28 |
29 | If you are developing with a team, you may wish to continue including a `.env.example` file with your application. By putting placeholder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application.
30 |
31 | > {tip} Any variable in your `.env` file can be overridden by external environment variables such as server-level or system-level environment variables.
32 |
33 |
34 | #### Environment File Security
35 |
36 | Your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository, since any sensitive credentials would get exposed.
37 |
38 |
39 | #### Additional Environment Files
40 |
41 | Before loading your application's environment variables, Laravel determines if either the `APP_ENV` environment variable has been externally provided or if the `--env` CLI argument has been specified. If so, Laravel will attempt to load an `.env.[APP_ENV]` file if it exists. If it does not exist, the default `.env` file will be loaded.
42 |
43 |
44 | ### Environment Variable Types
45 |
46 | All variables in your `.env` files are typically parsed as strings, so some reserved values have been created to allow you to return a wider range of types from the `env()` function:
47 |
48 | `.env` Value | `env()` Value
49 | ------------- | -------------
50 | true | (bool) true
51 | (true) | (bool) true
52 | false | (bool) false
53 | (false) | (bool) false
54 | empty | (string) ''
55 | (empty) | (string) ''
56 | null | (null) null
57 | (null) | (null) null
58 |
59 | If you need to define an environment variable with a value that contains spaces, you may do so by enclosing the value in double quotes:
60 |
61 | ```ini
62 | APP_NAME="My Application"
63 | ```
64 |
65 |
66 | ### Retrieving Environment Configuration
67 |
68 | All of the variables listed in this file will be loaded into the `$_ENV` PHP super-global when your application receives a request. However, you may use the `env` helper to retrieve values from these variables in your configuration files. In fact, if you review the Laravel configuration files, you will notice many of the options are already using this helper:
69 |
70 | 'debug' => env('APP_DEBUG', false),
71 |
72 | The second value passed to the `env` function is the "default value". This value will be returned if no environment variable exists for the given key.
73 |
74 |
75 | ### Determining The Current Environment
76 |
77 | The current application environment is determined via the `APP_ENV` variable from your `.env` file. You may access this value via the `environment` method on the `App` [facade](/docs/{{version}}/facades):
78 |
79 | use Illuminate\Support\Facades\App;
80 |
81 | $environment = App::environment();
82 |
83 | You may also pass arguments to the `environment` method to determine if the environment matches a given value. The method will return `true` if the environment matches any of the given values:
84 |
85 | if (App::environment('local')) {
86 | // The environment is local
87 | }
88 |
89 | if (App::environment(['local', 'staging'])) {
90 | // The environment is either local OR staging...
91 | }
92 |
93 | > {tip} The current application environment detection can be overridden by defining a server-level `APP_ENV` environment variable.
94 |
95 |
96 | ## Accessing Configuration Values
97 |
98 | You may easily access your configuration values using the global `config` helper function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exist:
99 |
100 | $value = config('app.timezone');
101 |
102 | // Retrieve a default value if the configuration value does not exist...
103 | $value = config('app.timezone', 'Asia/Seoul');
104 |
105 | To set configuration values at runtime, pass an array to the `config` helper:
106 |
107 | config(['app.timezone' => 'America/Chicago']);
108 |
109 |
110 | ## Configuration Caching
111 |
112 | To give your application a speed boost, you should cache all of your configuration files into a single file using the `config:cache` Artisan command. This will combine all of the configuration options for your application into a single file which can be quickly loaded by the framework.
113 |
114 | You should typically run the `php artisan config:cache` command as part of your production deployment process. The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development.
115 |
116 | > {note} If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded; therefore, the `env` function will only return external, system level environment variables.
117 |
118 |
119 | ## Debug Mode
120 |
121 | The `debug` option in your `config/app.php` configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the `APP_DEBUG` environment variable, which is stored in your `.env` file.
122 |
123 | For local development, you should set the `APP_DEBUG` environment variable to `true`. **In your production environment, this value should always be `false`. If the variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.**
124 |
125 |
126 | ## Maintenance Mode
127 |
128 | When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, a `Symfony\Component\HttpKernel\Exception\HttpException` instance will be thrown with a status code of 503.
129 |
130 | To enable maintenance mode, execute the `down` Artisan command:
131 |
132 | ```shell
133 | php artisan down
134 | ```
135 |
136 | If you would like the `Refresh` HTTP header to be sent with all maintenance mode responses, you may provide the `refresh` option when invoking the `down` command. The `Refresh` header will instruct the browser to automatically refresh the page after the specified number of seconds:
137 |
138 | ```shell
139 | php artisan down --refresh=15
140 | ```
141 |
142 | You may also provide a `retry` option to the `down` command, which will be set as the `Retry-After` HTTP header's value, although browsers generally ignore this header:
143 |
144 | ```shell
145 | php artisan down --retry=60
146 | ```
147 |
148 |
149 | #### Bypassing Maintenance Mode
150 |
151 | Even while in maintenance mode, you may use the `secret` option to specify a maintenance mode bypass token:
152 |
153 | ```shell
154 | php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
155 | ```
156 |
157 | After placing the application in maintenance mode, you may navigate to the application URL matching this token and Laravel will issue a maintenance mode bypass cookie to your browser:
158 |
159 | ```shell
160 | https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515
161 | ```
162 |
163 | When accessing this hidden route, you will then be redirected to the `/` route of the application. Once the cookie has been issued to your browser, you will be able to browse the application normally as if it was not in maintenance mode.
164 |
165 | > {tip} Your maintenance mode secret should typically consist of alpha-numeric characters and, optionally, dashes. You should avoid using characters that have special meaning in URLs such as `?`.
166 |
167 |
168 | #### Pre-Rendering The Maintenance Mode View
169 |
170 | If you utilize the `php artisan down` command during deployment, your users may still occasionally encounter errors if they access the application while your Composer dependencies or other infrastructure components are updating. This occurs because a significant part of the Laravel framework must boot in order to determine your application is in maintenance mode and render the maintenance mode view using the templating engine.
171 |
172 | For this reason, Laravel allows you to pre-render a maintenance mode view that will be returned at the very beginning of the request cycle. This view is rendered before any of your application's dependencies have loaded. You may pre-render a template of your choice using the `down` command's `render` option:
173 |
174 | ```shell
175 | php artisan down --render="errors::503"
176 | ```
177 |
178 |
179 | #### Redirecting Maintenance Mode Requests
180 |
181 | While in maintenance mode, Laravel will display the maintenance mode view for all application URLs the user attempts to access. If you wish, you may instruct Laravel to redirect all requests to a specific URL. This may be accomplished using the `redirect` option. For example, you may wish to redirect all requests to the `/` URI:
182 |
183 | ```shell
184 | php artisan down --redirect=/
185 | ```
186 |
187 |
188 | #### Disabling Maintenance Mode
189 |
190 | To disable maintenance mode, use the `up` command:
191 |
192 | ```shell
193 | php artisan up
194 | ```
195 |
196 | > {tip} You may customize the default maintenance mode template by defining your own template at `resources/views/errors/503.blade.php`.
197 |
198 |
199 | #### Maintenance Mode & Queues
200 |
201 | While your application is in maintenance mode, no [queued jobs](/docs/{{version}}/queues) will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode.
202 |
203 |
204 | #### Alternatives To Maintenance Mode
205 |
206 | Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like [Laravel Vapor](https://vapor.laravel.com) and [Envoyer](https://envoyer.io) to accomplish zero-downtime deployment with Laravel.
207 |
--------------------------------------------------------------------------------
/console-tests.md:
--------------------------------------------------------------------------------
1 | # Console Tests
2 |
3 | - [Introduction](#introduction)
4 | - [Success / Failure Expectations](#success-failure-expectations)
5 | - [Input / Output Expectations](#input-output-expectations)
6 |
7 |
8 | ## Introduction
9 |
10 | In addition to simplifying HTTP testing, Laravel provides a simple API for testing your application's [custom console commands](/docs/{{version}}/artisan).
11 |
12 |
13 | ## Success / Failure Expectations
14 |
15 | To get started, let's explore how to make assertions regarding an Artisan command's exit code. To accomplish this, we will use the `artisan` method to invoke an Artisan command from our test. Then, we will use the `assertExitCode` method to assert that the command completed with a given exit code:
16 |
17 | /**
18 | * Test a console command.
19 | *
20 | * @return void
21 | */
22 | public function test_console_command()
23 | {
24 | $this->artisan('inspire')->assertExitCode(0);
25 | }
26 |
27 | You may use the `assertNotExitCode` method to assert that the command did not exit with a given exit code:
28 |
29 | $this->artisan('inspire')->assertNotExitCode(1);
30 |
31 | Of course, all terminal commands typically exit with a status code of `0` when they are successful and a non-zero exit code when they are not successful. Therefore, for convenience, you may utilize the `assertSuccessful` and `assertFailed` assertions to assert that a given command exited with a successful exit code or not:
32 |
33 | $this->artisan('inspire')->assertSuccessful();
34 |
35 | $this->artisan('inspire')->assertFailed();
36 |
37 |
38 | ## Input / Output Expectations
39 |
40 | Laravel allows you to easily "mock" user input for your console commands using the `expectsQuestion` method. In addition, you may specify the exit code and text that you expect to be output by the console command using the `assertExitCode` and `expectsOutput` methods. For example, consider the following console command:
41 |
42 | Artisan::command('question', function () {
43 | $name = $this->ask('What is your name?');
44 |
45 | $language = $this->choice('Which language do you prefer?', [
46 | 'PHP',
47 | 'Ruby',
48 | 'Python',
49 | ]);
50 |
51 | $this->line('Your name is '.$name.' and you prefer '.$language.'.');
52 | });
53 |
54 | You may test this command with the following test which utilizes the `expectsQuestion`, `expectsOutput`, `doesntExpectOutput`, and `assertExitCode` methods:
55 |
56 | /**
57 | * Test a console command.
58 | *
59 | * @return void
60 | */
61 | public function test_console_command()
62 | {
63 | $this->artisan('question')
64 | ->expectsQuestion('What is your name?', 'Taylor Otwell')
65 | ->expectsQuestion('Which language do you prefer?', 'PHP')
66 | ->expectsOutput('Your name is Taylor Otwell and you prefer PHP.')
67 | ->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.')
68 | ->assertExitCode(0);
69 | }
70 |
71 |
72 | #### Confirmation Expectations
73 |
74 | When writing a command which expects confirmation in the form of a "yes" or "no" answer, you may utilize the `expectsConfirmation` method:
75 |
76 | $this->artisan('module:import')
77 | ->expectsConfirmation('Do you really wish to run this command?', 'no')
78 | ->assertExitCode(1);
79 |
80 |
81 | #### Table Expectations
82 |
83 | If your command displays a table of information using Artisan's `table` method, it can be cumbersome to write output expectations for the entire table. Instead, you may use the `expectsTable` method. This method accepts the table's headers as its first argument and the table's data as its second argument:
84 |
85 | $this->artisan('users:all')
86 | ->expectsTable([
87 | 'ID',
88 | 'Email',
89 | ], [
90 | [1, 'taylor@example.com'],
91 | [2, 'abigail@example.com'],
92 | ]);
93 |
--------------------------------------------------------------------------------
/contributions.md:
--------------------------------------------------------------------------------
1 | # دليل المساهمة
2 |
3 | - [تقارير الأخطاء](#bug-reports)
4 | - [أسئلة الدعم](#support-questions)
5 | - [نقاش التطوير الجوهري](#core-development-discussion)
6 | - [ أي فرع؟](#which-branch)
7 | - [الملفات المترجمة (Compiled Assets)](#compiled-assets)
8 | - [الثغرات الأمنية](#security-vulnerabilities)
9 | - [تنسيق الكود](#coding-style)
10 | - [توثيق PHP](#phpdoc)
11 | - [أداة StyleCI](#styleci)
12 | - [القواعد السلوكية](#code-of-conduct)
13 |
14 |
15 | ## تقارير الأخطاء
16 |
17 | لتشجيع التعاون النشط، لارافيل تشجع وبقوة طلبات السحب (pull requests)، بالإضافة لتقارير الأخطاء. ويمكن أيضاً إرسال "تقارير الأخطاء" بشكل طلب سحب (pull request) يحتوي على اختبار فشل. سيتم مراجعة طلبات السحب فقط عندما يتم تعليمها كـ"جاهزة للمراجعة" ("ready for review") وليست في حالة "مسودة" ("draft") وبعد اجتياز جميع الاختبارات للميزات الجديدة المضافة. سيتم إغلاق طلبات السحب العالقة وغير النشطة التي تركت في حالة "المسودة" بعد بضعة أيام.
18 |
19 | في كافة الأحوال، اذا قمت بتقديم تقرير خطأ، يجب أن تحتوي مشكلتك على على عنوان وشرح واضح للمشكلة. يجب عليك أيضاً تضمين أكبر قدر ممكن من المعلومات ذات الصلة وعينة من الكود البرمجي الذي يوضح المشكلة. إن الهدف من تقرير الخطأ هو تسهيل استنساخ الخطأ وتطوير حل للمشكلة لك وللمستخدمين الآخرين.
20 |
21 | تذكر، يتم إنشاء تقارير الأخطاء أملاً بأن الآخرين الذين يواجهون نفس المشكلة سيكونون قادرين على التعاون معك في حلها. لا تتوقع بأن تقرير الخطأ سوف يبحث في النشاطات تلقائياً أو أن الآخرين سيهبون لإصلاحه. إنشاء تقرير بالخطأ يأتي في صالحك أنت و الآخرين للبدء في مسار إصلاح المشكلة. إذا كنت تريد المشاركة، يمكنك المساعدة بإصلاح [أي مشكلة مدرجة في أدوات تعقب المشكلات الخاصة بنا](https://github.com/issues?q=is%3Aopen+is%3Aissue+label%3Abug+user%3Alaravel). يجب عليك أن تكون قد سجلت الدخول بغيت هاب (GitHub) لرؤية جميع مشكلات لارافيل.
22 |
23 | شيفرة المصدر (source code) الخاصة بلارافيل تتم إداراتها على غيت هاب (GitHub)، ومستودعاتهم لكل مشاريع لارافيل هي:
24 |
25 |
26 |
27 | - [تطبيق لارافيل (Laravel Application)](https://github.com/laravel/laravel)
28 | - [رسومات لارافيل (Laravel Art)](https://github.com/laravel/art)
29 | - [توثيق لارافيل (Laravel Documentation)](https://github.com/laravel/docs)
30 | - [لارافيل داسك (Laravel Dusk)](https://github.com/laravel/dusk)
31 | - [لارافيل كاشيير سترايب (Laravel Cashier Stripe)](https://github.com/laravel/cashier)
32 | - [لارافيل كاشيير بادل (Laravel Cashier Paddle)](https://github.com/laravel/cashier-paddle)
33 | - [لارافيل_ايكو (Laravel Echo)](https://github.com/laravel/echo)
34 | - [لارافيل اينفوي (Laravel Envoy)](https://github.com/laravel/envoy)
35 | - [إطار عمل لارافيل (Laravel Framework)](https://github.com/laravel/framework)
36 | - [لارافيل هومستيد (Laravel Homestead)](https://github.com/laravel/homestead)
37 | - [سكربتات بناء لارافيل هومستيد (Laravel Homestead Build Scripts)](https://github.com/laravel/settler)
38 | - [لارافيل هورايزن (Laravel Horizon)](https://github.com/laravel/horizon)
39 | - [لارافيل جيت ستريم (Laravel Jetstream)](https://github.com/laravel/jetstream)
40 | - [لارافيل باسبورت (Laravel Passport)](https://github.com/laravel/passport)
41 | - [لارافيل سيل (Laravel Sail)](https://github.com/laravel/sail)
42 | - [لارافيل سانكتوم (Laravel Sanctum)](https://github.com/laravel/sanctum)
43 | - [لارافيل سكاوت (Laravel Scout)](https://github.com/laravel/scout)
44 | - [لارافيل سوشيلايت (Laravel Socialite)](https://github.com/laravel/socialite)
45 | - [لارافيل تيليسكوب (Laravel Telescope)](https://github.com/laravel/telescope)
46 | - [موقع لارافيل (Laravel Website)](https://github.com/laravel/laravel.com-next)
47 |
48 |
49 |
50 |
51 | ## أسئلة الدعم
52 |
53 | أدوات تتبع أخطاء لارافيل على غيت هاب (GitHub) ليست لتقديم الدعم أو المساعدة بخصوص لارافيل. بدلاً من ذلك، استعمل احدى القنوات التالية لطلب المساعدة:
54 |
55 |
56 |
57 | - [GitHub Discussions](https://github.com/laravel/framework/discussions)
58 | - [Laracasts Forums](https://laracasts.com/discuss)
59 | - [Laravel.io Forums](https://laravel.io/forum)
60 | - [StackOverflow](https://stackoverflow.com/questions/tagged/laravel)
61 | - [Discord](https://discord.gg/laravel)
62 | - [Larachat](https://larachat.co)
63 | - [IRC](https://web.libera.chat/?nick=artisan&channels=#laravel)
64 |
65 |
66 |
67 |
68 | ## نقاش التطوير الجوهري
69 |
70 | يمكنك اقتراح ميزات أو تحسينات لسلوك لارافيل الموجود في مستودع (repository) إطار عمل لارافيل [مجلس المناقشة في غيت هاب (GitHub)](https://github.com/laravel/framework/discussions). اذا كنت تود اقتراح ميزة جديدة، رجاءً كن مستعداً لتنفيذ جزء من الكود البرمجي المطلوب على الأقل لاتمام الميزة.
71 |
72 | المناقشات الغير رسمية بخصوص المشاكل، الميزات الجديدة، وتنفيذ الميزات الحالية يحدث في قناة `#internals` الموجودة في [سيرفر لارافيل على ديسكورد](https://discord.gg/laravel). تايلور أوتويل، المشرف على لارافيل، عادة ما يكون متواجد على القناة في أيام الأسبوع من الساعة 8 صباحاً - وحتى الـ5 مساءً بتوقيت الولايات المتحدة الأمريكية (UTC-06:00 or America/Chicago)، ويكون حاضراً بشكل متقطع في القناة في أوقات أخرى.
73 |
74 |
75 | ## أي فرع؟
76 |
77 | **جميع** الإصلاحات يجب أن ترسل لاخر فرع (branch) مستقر. يجب **ألا** يتم ارسل الأخطاء التي تم اصلاحها للفرع الرئيسي `master` إلا في حال كان إصلاح لميزة موجودة فقط في إصدار قادم.
78 |
79 | قد يتم إرسال الميزات **الثانوية والمتوافقة تماماً مع الإصدارات السابقة** للإصدار الحالي إلى أحدث فرع مستقر.
80 |
81 | دائماً يجب إرسال الميزات الجديدة **الرئيسية** إلى الفرع الرئيسي `master`، الذي يحتوي على الإصدار القادم.
82 |
83 | إذا لم تكن متأكداً بأن ميزتك مؤهلة لتكون ميزة رئيسية أو ميزة ثانوية، رجاءً قم بسؤال تايلور أوتويل في قناة `#internals` الموجودة في [سيرفر لارافيل على ديسكورد](https://discord.gg/laravel).
84 |
85 |
86 | ## الملفات المترجمة (Compiled Assets)
87 |
88 | إذا كنت تقوم بتغيير يؤثر على ملف مترجم (compiled file)، مثل معظم الملفات الموجودة في `resources/css` أو `resources/js` في مستودع `laravel/laravel`، لا تقم بعمل (commit) للملفات المترجمة. لأنه ونظراً لحجمها الكبير، لايمكن مراجعتها بشكل واقعي وجيد من قبل المشرفين، حيث يمكن استغلال هذا الأمر لحقن كود ضار ضمن لارافيل. في إطار الحماية الدفاعية من هذه المشكلة، كل الملفات المترجمة سيتم إنشائها وعمل (commit) لها من قبل مشرفي لارافيل.
89 |
90 |
91 | ## الثغرات الأمنية
92 |
93 | اذا قمت باكتشاف ثغرة أمنية في لارافيل، رجاءً قم بإرسال بريد الكتروني لتايلور أوتويل على البريد التالي taylor@laravel.com. سيتم معالجة كل الثغرات الأمنية على الفور.
94 |
95 |
96 | ## تنسيق الكود
97 |
98 | تتبع لارافيل معيار التكويد [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) ومعيار التحميل التلقائي [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md).
99 |
100 |
101 | ### توثيق PHP
102 |
103 | المثال في الأسفل يعبر عن كتلة توثيق لارافيل سليمة، لاحظ بأن الخاصية `@param` متبوعة بفراغين، من ثم نوع الوسيط، من ثم فراغين، واسم المتحول في النهاية:
104 |
105 | /**
106 | * Register a binding with the container.
107 | *
108 | * @param string|array $abstract
109 | * @param \Closure|string|null $concrete
110 | * @param bool $shared
111 | * @return void
112 | *
113 | * @throws \Exception
114 | */
115 | public function bind($abstract, $concrete = null, $shared = false)
116 | {
117 | //
118 | }
119 |
120 |
121 | ### أداة StyleCI
122 |
123 | لا تقلق اذا كان تنسيق الكود الخاص بك غير مثالي! [أداة StyleCI](https://styleci.io/) تقوم اتوماتيكياً بإصلاح التنسيقات في مستودع لارافيل بعد دمج (merge) عملية سحب الطلب (pull requests). مما يمكننا من التركيز على محتوى المساهمة بدلاً من تنسيق الكود.
124 |
125 |
126 | ## القواعد السلوكية
127 |
128 | القواعد السلوكية الخاصة بلارافيل مشتقة من القواعد السلوكية الخاصة بروبي (Ruby). يمكن التبليغ عن أي انتهاكات للقواعد السلوكية لتايلور أوتويل (taylor@laravel.com):
129 |
130 |
131 |
132 | - يجب على المساهمين أن يكونو متسامحين ويتقبلو وجهات النظر المخالفة.
133 | - يجب على المساهمين التأكد من أن لغتهم وأفعالهم خالية من أي تهجم شخصي أو تعليقات شخصية مسيئة.
134 | - يجب على المساهمين عند تفسير أقوال وأفعال الآخرين افتراض حسن النية دوماً.
135 | - لن يتم التسامح مع أي سلوك يمكن اعتباره مضايقة.
136 |
137 |
--------------------------------------------------------------------------------
/csrf.md:
--------------------------------------------------------------------------------
1 | # الحماية من الطلبات المزورة عبر المواقع
2 |
3 | - [مقدمة](#csrf-introduction)
4 | - [منع الطلبات المزورة عبر المواقع](#preventing-csrf-requests)
5 | - [استثناء الروابط (URIs)](#csrf-excluding-uris)
6 | - [رمز (X-CSRF-TOKEN)](#csrf-x-csrf-token)
7 | - [رمز (X-XSRF-TOKEN)](#csrf-x-xsrf-token)
8 |
9 |
10 | ## مقدمة
11 |
12 | تزوير الطلبات عبر المواقع هو نوع من الثغرات الضارة حيث يتم تنفيذ أوامر غير مصرح بها نيابة عن المستخدم الموثق (authenticated user). لكن ولحسن الحظ، يقوم إطار عمل لارافيل بتسهيل حماية تطبيقك من [الطلبات المزورة عبر المواقع](https://en.wikipedia.org/wiki/Cross-site_request_forgery) أو مايعرف بهجمات الطلبات المزورة عبر المواقع (CSRF attacks).
13 |
14 |
15 | #### شرح للثغرة
16 |
17 | في حال أنك لم تسمع من قبل بالطلبات المزورة عبر الموقع، لنناقش مثالاً عن كيفية استغلال هذه الثغرة. لنتخيل بأن تطبيقك يحتوي المسار (route) التالي `/user/email` ويقبل طلب من الطريقة `POST` وهدفه تغيير عنوان البريد الالكتروني للمستخدم الموثق (authenticated user). غالباً هذا المسار (route) يقبل عنوان بريد الكتروني `email` كحقل إدخال يحوي على عنوان البريد الالكتروني للمستخدم الذي يود المستخدم البدء باستخدامه.
18 |
19 | بدون الحماية من الطلبات المزورة عبر المواقع (CSRF protection)، يمكن لأي موقع ضار إنشاء استمارة (HTML form) تشير للمسار (route) التالي `/user/email` في تطبيقك، فيقوم عندها المخترق بإرسل عنوان بريد الكتروني خاص به ليستبدل عنوان المستخدم الضحية في تطبيقك:
20 |
21 | ```blade
22 |
25 |
26 |
29 | ```
30 |
31 | إذا كان الموقع الضار يقوم اتوماتيكياً بإرسال الاستمارة (form) السابقة فور تحميل الصفحة، فإن المخترق يحتاج فقط لجذب المستخدم غير الحذر لزيارة موقعه وبمجرد زيارته للموقع الضار سيتم فوراً تغيير بريده الاكتروني في تطبيقك.
32 |
33 | لمنع هذه الثغرة، نحتاج لفحص الطلبات من نوع `POST`، `PUT`، `PATCH`، أو `DELETE` القادمة للتطبيق إن كانت تحتوي على قيمة سرية خاصة بالجلسة (session)، حيث لا يمكن للتطبيقات الضارة الوصول لها.
34 |
35 |
36 | ## منع الطلبات المزورة عبر المواقع
37 |
38 | يقوم إطار عمل لارافيل اوتوماتيكياً بإنشاء "رمز" لمنع الطلبات المزورة عبر المواقع (CSRF token) لكل [جلسة مستخدم](/docs/{{version}}/session) نشطة تتم إدارتها من قبل التطبيق. هذا الرمز (token) يستخدم للتحقق من أن المستخدم الموثق (authenticated user) هو الذي يقوم بإرسال الطلبات للتطبيق. وباعتبار أن هذا الرمز (token) مخزن في جلسة المستخدم ويتغير في كل مرة يتم فيها إعادة إنشاء الجلسة، فإن التطبيق الضار لا يستطيع الوصول لها.
39 |
40 | رمز منع الطلبات المزورة عبر المواقع (CSRF token) الحالي يمكن الوصول إليه بواسطة الطلب الخاص بالجلسة (request's session) أو بواسطة التابع المساعد (helper function) `csrf_token`:
41 |
42 | use Illuminate\Http\Request;
43 |
44 | Route::get('/token', function (Request $request) {
45 | $token = $request->session()->token();
46 |
47 | $token = csrf_token();
48 |
49 | // ...
50 | });
51 |
52 | في كل مرة تقوم فيها بإنشاء استمارة (HTML form) تحتوي على طلبات من نوع `POST`، `PUT`، `PATCH`، أو `DELETE` في تطبيقك، يجب عليك تضمين حقل مخفي لرمز ( CSRF `_token`) في الاستمارة (form) بحيث يمكن للبرمجية الوسيطة للحماية من الطلبات المزورة عبر المواقع (CSRF protection middleware) التحقق من الطلب. ولتسهيل تلك العملية، يمكنك استخدام الموجه (Blade directive) التالي `@csrf` الذي سيقوم بإنشاء حقل إدخال مخفي لرمز ( CSRF `_token`):
53 |
54 | ```blade
55 |
61 | ```
62 |
63 | [البرمجية الوسيطة (middleware)](/docs/{{version}}/middleware) `App\Http\Middleware\VerifyCsrfToken` والمضمنة بشكل افتراضي في مجموعة البرمجيات الوسيطة `web`
64 | أي (`web` middleware group)ستقوم بشكل تلقائي من التحقق من تطابق الرمز (CSRF token) الموجود ضمن الطلب والرمز المخزن ضمن الجلسة. وفي حال تطابق الرمزين يكون المستخدم هو من أرسل الطلب.
65 |
66 |
67 | ### رموز الحماية من الطلبات المزورة عبر المواقع وتطبيقات الصفحة الواحدة (SPA)
68 | في حال كان تطبيقك تطبيق بصفحة واحدة (SPA) يستخدم لارفيل كواجهة خلفية للتطبيق (backend API)، فعليك مراجعة [توثيق نظام المصادقة لارافيل سانكتوم (Laravel Sanctum)](/docs/{{version}}/sanctum) لمزيد من المعلومات حول المصادقة بالواجهة التطبيقية لبرنامجك (API) وحمايتها من ثغرات الطلبات المزورة عبر المواقع.
69 |
70 |
71 | ### استثناء الروابط (URI) من الحماية من الطلبات المزورة عبر المواقع
72 | في بعض الأحيان تحتاج لاستثناء مجموعة روابط (URIs) من الحماية من الطلبات المزورة عبر المواقع (CSRF protection). على سبيل المثال، اذا كنت تستخدم [سترايب (Stripe)](https://stripe.com) لمعالجة عمليات الدفع وتستفيد من نظام روابط الويب هوك (webhook system) الخاص به، فسوف تحتاج لاستثناء مسار معالج روابط الويب هوك الخاصة بسترايب (Stripe webhook handler route) من هذه الحماية لأن سترايب لا يعلم ما هو رمز (CSRF token) الذي يجب ارساله لمساراتك (routes).
73 |
74 | عادة، لاستثناء هذا النوع من المسارات (routes) يجب عليك وضعها خارج مجموعة البرمجيات الوسيطة (`web` middleware group) التي يقوم `App\Providers\RouteServiceProvider` بتطبيقها على جميع المسارات (routes) الموجودة في الملف `routes/web.php`. ولكن وبكل الأحوال يمكنك أيضاً استثناء المسارات (routes) بطريقة أخرى عبر وضع روابطها (URIs) في الخاصية `$except` في البرمجية الوسيطة (middleware) `VerifyCsrfToken`:
75 |
76 | {tip} للسهولة، تكون البرمجية الوسيطة معطلة تلقائياً لكل المسارات (routes) عند [إجراء الاختبارات](/docs/{{version}}/testing).
97 |
98 |
99 | ## رمز (X-CSRF-TOKEN)
100 |
101 | بالإضافة للتحقق من رمز (CSRF token) كوسيط في طريقة الإرسال POST ستقوم البرمجية الوسيطة `App\Http\Middleware\VerifyCsrfToken` أيضاً من بالتحقق من الترويسة (header) `X-CSRF-TOKEN` في الطلب، على سبيل المثال يمكنك تخزين الرمز في عنصر `meta` الخاص بلغة HTML:
102 |
103 |
104 | ```blade
105 |
106 | ```
107 | من ثم يمكنك استعمال مكتبة مثل جي كويري (jQuery) لإضافة الرمز (token) تلقائياً لجميع ترويسات الطلبات. مما يوفر حماية سهلة وبسيطة من الطلبات المزورة عبر المواقع لتطبيقك الذي يعتمد على اجاكس (AJAX) باستعمال تقنية قديمة لجافاسكريبت (JavaScript) :
108 |
109 | ```js
110 | $.ajaxSetup({
111 | headers: {
112 | 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
113 | }
114 | });
115 | ```
116 |
117 |
118 | ## رمز (X-XSRF-TOKEN)
119 |
120 | يقوم إطار عمل لارافيل بتخزين رمز (CSRF token) ضمن كوكي (cookie) كرمز مشفر `XSRF-TOKEN` ويقوم بتضمينها في كل رد يقوم بانشائه. حيث يمكنك استعمال قيمة الكوكي (cookie) تلك كقيمة لترويسة `X-XSRF-TOKEN` ضمن الطلب.
121 |
122 | يتم إرسال هذه الكوكي (cookie) بشكل أساسي لتسهيل عمل المطور حيث أن بعض اطر عمل ومكتبات جافاسكريبت (JavaScript) مثل أنغيولر (Angular) وأكسيوس (Axios)، تقوم بشكل تلقائي بوضع قيمة الترويسة `X-XSRF-TOKEN` على الطلبات من نفس المصدر.
123 |
124 | > {tip} بشكل افترضي، يحتوي الملف `resources/js/bootstrap.js` على مكتبة HTTP الخاصة باكسيوس (Axios) التي ستقوم وبشكل تلقائي بإرسال ترويسة `X-XSRF-TOKEN` لك.
125 |
--------------------------------------------------------------------------------
/deployment.md:
--------------------------------------------------------------------------------
1 | # Deployment
2 |
3 | - [Introduction](#introduction)
4 | - [Server Requirements](#server-requirements)
5 | - [Server Configuration](#server-configuration)
6 | - [Nginx](#nginx)
7 | - [Optimization](#optimization)
8 | - [Autoloader Optimization](#autoloader-optimization)
9 | - [Optimizing Configuration Loading](#optimizing-configuration-loading)
10 | - [Optimizing Route Loading](#optimizing-route-loading)
11 | - [Optimizing View Loading](#optimizing-view-loading)
12 | - [Debug Mode](#debug-mode)
13 | - [Deploying With Forge / Vapor](#deploying-with-forge-or-vapor)
14 |
15 |
16 | ## Introduction
17 |
18 | When you're ready to deploy your Laravel application to production, there are some important things you can do to make sure your application is running as efficiently as possible. In this document, we'll cover some great starting points for making sure your Laravel application is deployed properly.
19 |
20 |
21 | ## Server Requirements
22 |
23 | The Laravel framework has a few system requirements. You should ensure that your web server has the following minimum PHP version and extensions:
24 |
25 |
26 |
27 | - PHP >= 8.0
28 | - BCMath PHP Extension
29 | - Ctype PHP Extension
30 | - DOM PHP Extension
31 | - Fileinfo PHP Extension
32 | - JSON PHP Extension
33 | - Mbstring PHP Extension
34 | - OpenSSL PHP Extension
35 | - PCRE PHP Extension
36 | - PDO PHP Extension
37 | - Tokenizer PHP Extension
38 | - XML PHP Extension
39 |
40 |
41 |
42 |
43 | ## Server Configuration
44 |
45 |
46 | ### Nginx
47 |
48 | If you are deploying your application to a server that is running Nginx, you may use the following configuration file as a starting point for configuring your web server. Most likely, this file will need to be customized depending on your server's configuration. **If you would like assistance in managing your server, consider using a first-party Laravel server management and deployment service such as [Laravel Forge](https://forge.laravel.com).**
49 |
50 | Please ensure, like the configuration below, your web server directs all requests to your application's `public/index.php` file. You should never attempt to move the `index.php` file to your project's root, as serving the application from the project root will expose many sensitive configuration files to the public Internet:
51 |
52 | ```nginx
53 | server {
54 | listen 80;
55 | listen [::]:80;
56 | server_name example.com;
57 | root /srv/example.com/public;
58 |
59 | add_header X-Frame-Options "SAMEORIGIN";
60 | add_header X-Content-Type-Options "nosniff";
61 |
62 | index index.php;
63 |
64 | charset utf-8;
65 |
66 | location / {
67 | try_files $uri $uri/ /index.php?$query_string;
68 | }
69 |
70 | location = /favicon.ico { access_log off; log_not_found off; }
71 | location = /robots.txt { access_log off; log_not_found off; }
72 |
73 | error_page 404 /index.php;
74 |
75 | location ~ \.php$ {
76 | fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
77 | fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
78 | include fastcgi_params;
79 | }
80 |
81 | location ~ /\.(?!well-known).* {
82 | deny all;
83 | }
84 | }
85 | ```
86 |
87 |
88 | ## Optimization
89 |
90 |
91 | ### Autoloader Optimization
92 |
93 | When deploying to production, make sure that you are optimizing Composer's class autoloader map so Composer can quickly find the proper file to load for a given class:
94 |
95 | ```shell
96 | composer install --optimize-autoloader --no-dev
97 | ```
98 |
99 | > {tip} In addition to optimizing the autoloader, you should always be sure to include a `composer.lock` file in your project's source control repository. Your project's dependencies can be installed much faster when a `composer.lock` file is present.
100 |
101 |
102 | ### Optimizing Configuration Loading
103 |
104 | When deploying your application to production, you should make sure that you run the `config:cache` Artisan command during your deployment process:
105 |
106 | ```shell
107 | php artisan config:cache
108 | ```
109 |
110 | This command will combine all of Laravel's configuration files into a single, cached file, which greatly reduces the number of trips the framework must make to the filesystem when loading your configuration values.
111 |
112 | > {note} If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls to the `env` function for `.env` variables will return `null`.
113 |
114 |
115 | ### Optimizing Route Loading
116 |
117 | If you are building a large application with many routes, you should make sure that you are running the `route:cache` Artisan command during your deployment process:
118 |
119 | ```shell
120 | php artisan route:cache
121 | ```
122 |
123 | This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
124 |
125 |
126 | ### Optimizing View Loading
127 |
128 | When deploying your application to production, you should make sure that you run the `view:cache` Artisan command during your deployment process:
129 |
130 | ```shell
131 | php artisan view:cache
132 | ```
133 |
134 | This command precompiles all your Blade views so they are not compiled on demand, improving the performance of each request that returns a view.
135 |
136 |
137 | ## Debug Mode
138 |
139 | The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.
140 |
141 | **In your production environment, this value should always be `false`. If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.**
142 |
143 |
144 | ## Deploying With Forge / Vapor
145 |
146 |
147 | #### Laravel Forge
148 |
149 | If you aren't quite ready to manage your own server configuration or aren't comfortable configuring all of the various services needed to run a robust Laravel application, [Laravel Forge](https://forge.laravel.com) is a wonderful alternative.
150 |
151 | Laravel Forge can create servers on various infrastructure providers such as DigitalOcean, Linode, AWS, and more. In addition, Forge installs and manages all of the tools needed to build robust Laravel applications, such as Nginx, MySQL, Redis, Memcached, Beanstalk, and more.
152 |
153 |
154 | #### Laravel Vapor
155 |
156 | If you would like a totally serverless, auto-scaling deployment platform tuned for Laravel, check out [Laravel Vapor](https://vapor.laravel.com). Laravel Vapor is a serverless deployment platform for Laravel, powered by AWS. Launch your Laravel infrastructure on Vapor and fall in love with the scalable simplicity of serverless. Laravel Vapor is fine-tuned by Laravel's creators to work seamlessly with the framework so you can keep writing your Laravel applications exactly like you're used to.
157 |
--------------------------------------------------------------------------------
/dictionary.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | Phrase | Translation | Explanation
4 | ------------- | ------------- | -----------
5 | Resolve Resolving Resolved | استبيان أو الحصول على | Because resolving an object out of the service container basically means that the service container handles building up the needed dependencies and requirements to hand over an object that is ready to do it’s work.
6 | Class | كائن | Because in programming languages, if a class does not inherit from any other class, it automatically inherits from an object
7 | Method | طريقة أو تابع | -
8 | Container | حاوية | -
9 | Object | غرض أو كائن | -
10 | Instance | غرض أو نسخة | -
11 | Static | ستاتيكي | -
12 | Stub | نموذج القابل للاستبدال | -
13 | Real-time | أثناء التنفيذ | -
14 | Namespace | نطاق الأسماء | -
15 | Scope Creep | تمدد نطاق أو زحف النطاق | -
16 | Cache System | نظام الذاكرة المؤقت | -
17 |
--------------------------------------------------------------------------------
/documentation.md:
--------------------------------------------------------------------------------
1 | - ## Prologue
2 | - [Release Notes](/docs/{{version}}/releases)
3 | - [Upgrade Guide](/docs/{{version}}/upgrade)
4 | - [Contribution Guide](/docs/{{version}}/contributions)
5 | - ## Getting Started
6 | - [Installation](/docs/{{version}}/installation)
7 | - [Configuration](/docs/{{version}}/configuration)
8 | - [Directory Structure](/docs/{{version}}/structure)
9 | - [Starter Kits](/docs/{{version}}/starter-kits)
10 | - [Deployment](/docs/{{version}}/deployment)
11 | - ## Architecture Concepts
12 | - [Request Lifecycle](/docs/{{version}}/lifecycle)
13 | - [Service Container](/docs/{{version}}/container)
14 | - [Service Providers](/docs/{{version}}/providers)
15 | - [Facades](/docs/{{version}}/facades)
16 | - ## The Basics
17 | - [Routing](/docs/{{version}}/routing)
18 | - [Middleware](/docs/{{version}}/middleware)
19 | - [CSRF Protection](/docs/{{version}}/csrf)
20 | - [Controllers](/docs/{{version}}/controllers)
21 | - [Requests](/docs/{{version}}/requests)
22 | - [Responses](/docs/{{version}}/responses)
23 | - [Views](/docs/{{version}}/views)
24 | - [Blade Templates](/docs/{{version}}/blade)
25 | - [URL Generation](/docs/{{version}}/urls)
26 | - [Session](/docs/{{version}}/session)
27 | - [Validation](/docs/{{version}}/validation)
28 | - [Error Handling](/docs/{{version}}/errors)
29 | - [Logging](/docs/{{version}}/logging)
30 | - ## Digging Deeper
31 | - [Artisan Console](/docs/{{version}}/artisan)
32 | - [Broadcasting](/docs/{{version}}/broadcasting)
33 | - [Cache](/docs/{{version}}/cache)
34 | - [Collections](/docs/{{version}}/collections)
35 | - [Compiling Assets](/docs/{{version}}/mix)
36 | - [Contracts](/docs/{{version}}/contracts)
37 | - [Events](/docs/{{version}}/events)
38 | - [File Storage](/docs/{{version}}/filesystem)
39 | - [Helpers](/docs/{{version}}/helpers)
40 | - [HTTP Client](/docs/{{version}}/http-client)
41 | - [Localization](/docs/{{version}}/localization)
42 | - [Mail](/docs/{{version}}/mail)
43 | - [Notifications](/docs/{{version}}/notifications)
44 | - [Package Development](/docs/{{version}}/packages)
45 | - [Queues](/docs/{{version}}/queues)
46 | - [Rate Limiting](/docs/{{version}}/rate-limiting)
47 | - [Task Scheduling](/docs/{{version}}/scheduling)
48 | - ## Security
49 | - [Authentication](/docs/{{version}}/authentication)
50 | - [Authorization](/docs/{{version}}/authorization)
51 | - [Email Verification](/docs/{{version}}/verification)
52 | - [Encryption](/docs/{{version}}/encryption)
53 | - [Hashing](/docs/{{version}}/hashing)
54 | - [Password Reset](/docs/{{version}}/passwords)
55 | - ## Database
56 | - [Getting Started](/docs/{{version}}/database)
57 | - [Query Builder](/docs/{{version}}/queries)
58 | - [Pagination](/docs/{{version}}/pagination)
59 | - [Migrations](/docs/{{version}}/migrations)
60 | - [Seeding](/docs/{{version}}/seeding)
61 | - [Redis](/docs/{{version}}/redis)
62 | - ## Eloquent ORM
63 | - [Getting Started](/docs/{{version}}/eloquent)
64 | - [Relationships](/docs/{{version}}/eloquent-relationships)
65 | - [Collections](/docs/{{version}}/eloquent-collections)
66 | - [Mutators / Casts](/docs/{{version}}/eloquent-mutators)
67 | - [API Resources](/docs/{{version}}/eloquent-resources)
68 | - [Serialization](/docs/{{version}}/eloquent-serialization)
69 | - ## Testing
70 | - [Getting Started](/docs/{{version}}/testing)
71 | - [HTTP Tests](/docs/{{version}}/http-tests)
72 | - [Console Tests](/docs/{{version}}/console-tests)
73 | - [Browser Tests](/docs/{{version}}/dusk)
74 | - [Database](/docs/{{version}}/database-testing)
75 | - [Mocking](/docs/{{version}}/mocking)
76 | - ## Packages
77 | - [Breeze](/docs/{{version}}/starter-kits#laravel-breeze)
78 | - [Cashier (Stripe)](/docs/{{version}}/billing)
79 | - [Cashier (Paddle)](/docs/{{version}}/cashier-paddle)
80 | - [Dusk](/docs/{{version}}/dusk)
81 | - [Envoy](/docs/{{version}}/envoy)
82 | - [Fortify](/docs/{{version}}/fortify)
83 | - [Homestead](/docs/{{version}}/homestead)
84 | - [Horizon](/docs/{{version}}/horizon)
85 | - [Jetstream](https://jetstream.laravel.com)
86 | - [Octane](/docs/{{version}}/octane)
87 | - [Passport](/docs/{{version}}/passport)
88 | - [Sail](/docs/{{version}}/sail)
89 | - [Sanctum](/docs/{{version}}/sanctum)
90 | - [Scout](/docs/{{version}}/scout)
91 | - [Socialite](/docs/{{version}}/socialite)
92 | - [Telescope](/docs/{{version}}/telescope)
93 | - [Valet](/docs/{{version}}/valet)
94 | - [API Documentation](/api/9.x)
95 |
--------------------------------------------------------------------------------
/eloquent-collections.md:
--------------------------------------------------------------------------------
1 | # Eloquent: Collections
2 |
3 | - [Introduction](#introduction)
4 | - [Available Methods](#available-methods)
5 | - [Custom Collections](#custom-collections)
6 |
7 |
8 | ## Introduction
9 |
10 | All Eloquent methods that return more than one model result will return instances of the `Illuminate\Database\Eloquent\Collection` class, including results retrieved via the `get` method or accessed via a relationship. The Eloquent collection object extends Laravel's [base collection](/docs/{{version}}/collections), so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!
11 |
12 | All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
13 |
14 | use App\Models\User;
15 |
16 | $users = User::where('active', 1)->get();
17 |
18 | foreach ($users as $user) {
19 | echo $user->name;
20 | }
21 |
22 | However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user:
23 |
24 | $names = User::all()->reject(function ($user) {
25 | return $user->active === false;
26 | })->map(function ($user) {
27 | return $user->name;
28 | });
29 |
30 |
31 | #### Eloquent Collection Conversion
32 |
33 | While most Eloquent collection methods return a new instance of an Eloquent collection, the `collapse`, `flatten`, `flip`, `keys`, `pluck`, and `zip` methods return a [base collection](/docs/{{version}}/collections) instance. Likewise, if a `map` operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance.
34 |
35 |
36 | ## Available Methods
37 |
38 | All Eloquent collections extend the base [Laravel collection](/docs/{{version}}/collections#available-methods) object; therefore, they inherit all of the powerful methods provided by the base collection class.
39 |
40 | In addition, the `Illuminate\Database\Eloquent\Collection` class provides a superset of methods to aid with managing your model collections. Most methods return `Illuminate\Database\Eloquent\Collection` instances; however, some methods, like `modelKeys`, return an `Illuminate\Support\Collection` instance.
41 |
42 |
60 |
61 |
62 |
63 | [contains](#method-contains)
64 | [diff](#method-diff)
65 | [except](#method-except)
66 | [find](#method-find)
67 | [fresh](#method-fresh)
68 | [intersect](#method-intersect)
69 | [load](#method-load)
70 | [loadMissing](#method-loadMissing)
71 | [modelKeys](#method-modelKeys)
72 | [makeVisible](#method-makeVisible)
73 | [makeHidden](#method-makeHidden)
74 | [only](#method-only)
75 | [toQuery](#method-toquery)
76 | [unique](#method-unique)
77 |
78 |
79 |
80 |
81 | #### `contains($key, $operator = null, $value = null)` {.collection-method .first-collection-method}
82 |
83 | The `contains` method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:
84 |
85 | $users->contains(1);
86 |
87 | $users->contains(User::find(1));
88 |
89 |
90 | #### `diff($items)` {.collection-method}
91 |
92 | The `diff` method returns all of the models that are not present in the given collection:
93 |
94 | use App\Models\User;
95 |
96 | $users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
97 |
98 |
99 | #### `except($keys)` {.collection-method}
100 |
101 | The `except` method returns all of the models that do not have the given primary keys:
102 |
103 | $users = $users->except([1, 2, 3]);
104 |
105 |
106 | #### `find($key)` {.collection-method}
107 |
108 | The `find` method returns the model that has a primary key matching the given key. If `$key` is a model instance, `find` will attempt to return a model matching the primary key. If `$key` is an array of keys, `find` will return all models which have a primary key in the given array:
109 |
110 | $users = User::all();
111 |
112 | $user = $users->find(1);
113 |
114 |
115 | #### `fresh($with = [])` {.collection-method}
116 |
117 | The `fresh` method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded:
118 |
119 | $users = $users->fresh();
120 |
121 | $users = $users->fresh('comments');
122 |
123 |
124 | #### `intersect($items)` {.collection-method}
125 |
126 | The `intersect` method returns all of the models that are also present in the given collection:
127 |
128 | use App\Models\User;
129 |
130 | $users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());
131 |
132 |
133 | #### `load($relations)` {.collection-method}
134 |
135 | The `load` method eager loads the given relationships for all models in the collection:
136 |
137 | $users->load(['comments', 'posts']);
138 |
139 | $users->load('comments.author');
140 |
141 |
142 | #### `loadMissing($relations)` {.collection-method}
143 |
144 | The `loadMissing` method eager loads the given relationships for all models in the collection if the relationships are not already loaded:
145 |
146 | $users->loadMissing(['comments', 'posts']);
147 |
148 | $users->loadMissing('comments.author');
149 |
150 |
151 | #### `modelKeys()` {.collection-method}
152 |
153 | The `modelKeys` method returns the primary keys for all models in the collection:
154 |
155 | $users->modelKeys();
156 |
157 | // [1, 2, 3, 4, 5]
158 |
159 |
160 | #### `makeVisible($attributes)` {.collection-method}
161 |
162 | The `makeVisible` method [makes attributes visible](/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json) that are typically "hidden" on each model in the collection:
163 |
164 | $users = $users->makeVisible(['address', 'phone_number']);
165 |
166 |
167 | #### `makeHidden($attributes)` {.collection-method}
168 |
169 | The `makeHidden` method [hides attributes](/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json) that are typically "visible" on each model in the collection:
170 |
171 | $users = $users->makeHidden(['address', 'phone_number']);
172 |
173 |
174 | #### `only($keys)` {.collection-method}
175 |
176 | The `only` method returns all of the models that have the given primary keys:
177 |
178 | $users = $users->only([1, 2, 3]);
179 |
180 |
181 | #### `toQuery()` {.collection-method}
182 |
183 | The `toQuery` method returns an Eloquent query builder instance containing a `whereIn` constraint on the collection model's primary keys:
184 |
185 | use App\Models\User;
186 |
187 | $users = User::where('status', 'VIP')->get();
188 |
189 | $users->toQuery()->update([
190 | 'status' => 'Administrator',
191 | ]);
192 |
193 |
194 | #### `unique($key = null, $strict = false)` {.collection-method}
195 |
196 | The `unique` method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed:
197 |
198 | $users = $users->unique();
199 |
200 |
201 | ## Custom Collections
202 |
203 | If you would like to use a custom `Collection` object when interacting with a given model, you may define a `newCollection` method on your model:
204 |
205 |
12 | ## Introduction
13 |
14 | When building APIs using Laravel, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models.
15 |
16 | > {tip} For an even more robust way of handling Eloquent model and collection JSON serialization, check out the documentation on [Eloquent API resources](/docs/{{version}}/eloquent-resources).
17 |
18 |
19 | ## Serializing Models & Collections
20 |
21 |
22 | ### Serializing To Arrays
23 |
24 | To convert a model and its loaded [relationships](/docs/{{version}}/eloquent-relationships) to an array, you should use the `toArray` method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
25 |
26 | use App\Models\User;
27 |
28 | $user = User::with('roles')->first();
29 |
30 | return $user->toArray();
31 |
32 | The `attributesToArray` method may be used to convert a model's attributes to an array but not its relationships:
33 |
34 | $user = User::first();
35 |
36 | return $user->attributesToArray();
37 |
38 | You may also convert entire [collections](/docs/{{version}}/eloquent-collections) of models to arrays by calling the `toArray` method on the collection instance:
39 |
40 | $users = User::all();
41 |
42 | return $users->toArray();
43 |
44 |
45 | ### Serializing To JSON
46 |
47 | To convert a model to JSON, you should use the `toJson` method. Like `toArray`, the `toJson` method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are [supported by PHP](https://secure.php.net/manual/en/function.json-encode.php):
48 |
49 | use App\Models\User;
50 |
51 | $user = User::find(1);
52 |
53 | return $user->toJson();
54 |
55 | return $user->toJson(JSON_PRETTY_PRINT);
56 |
57 | Alternatively, you may cast a model or collection to a string, which will automatically call the `toJson` method on the model or collection:
58 |
59 | return (string) User::find(1);
60 |
61 | Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers:
62 |
63 | Route::get('users', function () {
64 | return User::all();
65 | });
66 |
67 |
68 | #### Relationships
69 |
70 | When an Eloquent model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object. Also, though Eloquent relationship methods are defined using "camel case" method names, a relationship's JSON attribute will be "snake case".
71 |
72 |
73 | ## Hiding Attributes From JSON
74 |
75 | Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a `$hidden` property to your model. In attributes that are listed in the `$hidden` property's array will not be included in the serialized representation of your model:
76 |
77 | {tip} To hide relationships, add the relationship's method name to your Eloquent model's `$hidden` property.
94 |
95 | Alternatively, you may use the `visible` property to define an "allow list" of attributes that should be included in your model's array and JSON representation. All attributes that are not present in the `$visible` array will be hidden when the model is converted to an array or JSON:
96 |
97 |
114 | #### Temporarily Modifying Attribute Visibility
115 |
116 | If you would like to make some typically hidden attributes visible on a given model instance, you may use the `makeVisible` method. The `makeVisible` method returns the model instance:
117 |
118 | return $user->makeVisible('attribute')->toArray();
119 |
120 | Likewise, if you would like to hide some attributes that are typically visible, you may use the `makeHidden` method.
121 |
122 | return $user->makeHidden('attribute')->toArray();
123 |
124 |
125 | ## Appending Values To JSON
126 |
127 | Occasionally, when converting models to arrays 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](/docs/{{version}}/eloquent-mutators) for the value:
128 |
129 | 'yes',
147 | );
148 | }
149 | }
150 |
151 | After creating the accessor, add the attribute name to the `appends` property of your model. Note that attribute names are typically referenced using their "snake case" serialized representation, even though the accessor's PHP method is defined using "camel case":
152 |
153 |
172 | #### Appending At Run Time
173 |
174 | At runtime, you may instruct a model instance to append additional attributes using the `append` method. Or, you may use the `setAppends` method to override the entire array of appended properties for a given model instance:
175 |
176 | return $user->append('is_admin')->toArray();
177 |
178 | return $user->setAppends(['is_admin'])->toArray();
179 |
180 |
181 | ## Date Serialization
182 |
183 |
184 | #### Customizing The Default Date Format
185 |
186 | You may customize the default serialization format by overriding the `serializeDate` method. This method does not affect how your dates are formatted for storage in the database:
187 |
188 | /**
189 | * Prepare a date for array / JSON serialization.
190 | *
191 | * @param \DateTimeInterface $date
192 | * @return string
193 | */
194 | protected function serializeDate(DateTimeInterface $date)
195 | {
196 | return $date->format('Y-m-d');
197 | }
198 |
199 |
200 | #### Customizing The Date Format Per Attribute
201 |
202 | You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the model's [cast declarations](/docs/{{version}}/eloquent-mutators#attribute-casting):
203 |
204 | protected $casts = [
205 | 'birthday' => 'date:Y-m-d',
206 | 'joined_at' => 'datetime:Y-m-d H:00',
207 | ];
208 |
--------------------------------------------------------------------------------
/encryption.md:
--------------------------------------------------------------------------------
1 | # التشفير
2 |
3 | - [مقدمة](#مقدمة)
4 | - [الضبط والاعداد](#الضبط-والاعداد)
5 | - [استخدام التشفير](#استخدام-التشفير)
6 |
7 |
8 | ## مقدمة
9 |
10 | توفر خدمات التشفير في Laravel واجهة بسيطة ومريحة لتشفير وفك تشفير النص عبر OpenSSL باستخدام تشفير AES-256 و AES-128. يتم توقيع جميع قيم Laravel المشفرة باستخدام رمز مصادقة الرسالة (MAC) بحيث لا يمكن تعديل قيمتها الأساسية أو العبث بها بمجرد تشفيرها.
11 |
12 |
13 | ## الضبط والاعداد
14 |
15 | قبل البدء باستخدام التشفير في Laravel, يجب عليك اولاً ضبط قيمة المفتاح `key` ضمن ملف التكوين الخاص بك أي ضمن `config/app.php`. هذه القيمة تعتمد على قيمة متغيير البيئة `APP_KEY`. يجب عليك استخدام الأمر `php artisan key:generate` حتى تولّد قيمة متغيّر البيئة هذا حيث أن الأمر `key:generate` سيستخدم منشئ البايت العشوائي الآمن (secure random bytes generator) الخاص بـ PHP لإنشاء مفتاح آمن مشفر لتطبيقك. عادةً, ما يتم توليد قيمة متغيّر البيئة `APP_KEY` الخاص بك خلال مرحلة [تثبيت Laravel] (/docs/{{version}}/installation).
16 |
17 |
18 | ## استخدام التشفير
19 |
20 |
21 | #### تشفير قيمة ما
22 |
23 | يمكنك تشفير قيمة ما باستخدام طريقة `encryptString` التي توفرها الواجهة `Crypt`. يتم تشفير جميع القيم المراد تشفيرها باستخدام تشفير OpenSSL و AES-256-CBC. علاوة على ذلك ، يتم توقيع جميع القيم المشفرة برمز مصادقة الرسالة (MAC). سيمنع رمز مصادقة الرسالة المتكاملة فك تشفير أي قيمة تم العبث بها من قبل المستخدمين الضارين (أي سوف يمنع التلاعب بالبيانات ويضمن التكامل):
24 |
25 | user()->fill([
45 | 'token' => Crypt::encryptString($request->token),
46 | ])->save();
47 | }
48 | }
49 |
50 |
51 | #### فك تشفير قيمة ما
52 |
53 | يمكنك فك تشفير قيمة ما باستخدام طريقة `decryptString` التي توفرها الواجهة` Crypt`. إذا تعذر فك تشفير القيمة بشكل صحيح ، كما هو الحال عندما يكون رمز مصادقة الرسالة غير صالح ، فسيتم اطلاق الاستثناء التالي `Illuminate \ Contracts \ Encryption \ DecryptException`:
54 |
55 | use Illuminate\Contracts\Encryption\DecryptException;
56 | use Illuminate\Support\Facades\Crypt;
57 |
58 | try {
59 | $decrypted = Crypt::decryptString($encryptedValue);
60 | } catch (DecryptException $e) {
61 | //
62 | }
63 |
--------------------------------------------------------------------------------
/envoy.md:
--------------------------------------------------------------------------------
1 | # Laravel Envoy
2 |
3 | - [Introduction](#introduction)
4 | - [Installation](#installation)
5 | - [Writing Tasks](#writing-tasks)
6 | - [Defining Tasks](#defining-tasks)
7 | - [Multiple Servers](#multiple-servers)
8 | - [Setup](#setup)
9 | - [Variables](#variables)
10 | - [Stories](#stories)
11 | - [Hooks](#completion-hooks)
12 | - [Running Tasks](#running-tasks)
13 | - [Confirming Task Execution](#confirming-task-execution)
14 | - [Notifications](#notifications)
15 | - [Slack](#slack)
16 | - [Discord](#discord)
17 | - [Telegram](#telegram)
18 | - [Microsoft Teams](#microsoft-teams)
19 |
20 |
21 | ## Introduction
22 |
23 | [Laravel Envoy](https://github.com/laravel/envoy) is a tool for executing common tasks you run on your remote servers. Using [Blade](/docs/{{version}}/blade) style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems. However, Windows support is achievable using [WSL2](https://docs.microsoft.com/en-us/windows/wsl/install-win10).
24 |
25 |
26 | ## Installation
27 |
28 | First, install Envoy into your project using the Composer package manager:
29 |
30 | ```shell
31 | composer require laravel/envoy --dev
32 | ```
33 |
34 | Once Envoy has been installed, the Envoy binary will be available in your application's `vendor/bin` directory:
35 |
36 | ```shell
37 | php vendor/bin/envoy
38 | ```
39 |
40 |
41 | ## Writing Tasks
42 |
43 |
44 | ### Defining Tasks
45 |
46 | Tasks are the basic building block of Envoy. Tasks define the shell commands that should execute on your remote servers when the task is invoked. For example, you might define a task that executes the `php artisan queue:restart` command on all of your application's queue worker servers.
47 |
48 | All of your Envoy tasks should be defined in an `Envoy.blade.php` file at the root of your application. Here's an example to get you started:
49 |
50 | ```blade
51 | @servers(['web' => ['user@192.168.1.1'], 'workers' => ['user@192.168.1.2']])
52 |
53 | @task('restart-queues', ['on' => 'workers'])
54 | cd /home/user/example.com
55 | php artisan queue:restart
56 | @endtask
57 | ```
58 |
59 | As you can see, an array of `@servers` is defined at the top of the file, allowing you to reference these servers via the `on` option of your task declarations. The `@servers` declaration should always be placed on a single line. Within your `@task` declarations, you should place the shell commands that should execute on your servers when the task is invoked.
60 |
61 |
62 | #### Local Tasks
63 |
64 | You can force a script to run on your local computer by specifying the server's IP address as `127.0.0.1`:
65 |
66 | ```blade
67 | @servers(['localhost' => '127.0.0.1'])
68 | ```
69 |
70 |
71 | #### Importing Envoy Tasks
72 |
73 | Using the `@import` directive, you may import other Envoy files so their stories and tasks are added to yours. After the files have been imported, you may execute the tasks they contain as if they were defined in your own Envoy file:
74 |
75 | ```blade
76 | @import('vendor/package/Envoy.blade.php')
77 | ```
78 |
79 |
80 | ### Multiple Servers
81 |
82 | Envoy allows you to easily run a task across multiple servers. First, add additional servers to your `@servers` declaration. Each server should be assigned a unique name. Once you have defined your additional servers you may list each of the servers in the task's `on` array:
83 |
84 | ```blade
85 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
86 |
87 | @task('deploy', ['on' => ['web-1', 'web-2']])
88 | cd /home/user/example.com
89 | git pull origin {{ $branch }}
90 | php artisan migrate --force
91 | @endtask
92 | ```
93 |
94 |
95 | #### Parallel Execution
96 |
97 | By default, tasks will be executed on each server serially. In other words, a task will finish running on the first server before proceeding to execute on the second server. If you would like to run a task across multiple servers in parallel, add the `parallel` option to your task declaration:
98 |
99 | ```blade
100 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
101 |
102 | @task('deploy', ['on' => ['web-1', 'web-2'], 'parallel' => true])
103 | cd /home/user/example.com
104 | git pull origin {{ $branch }}
105 | php artisan migrate --force
106 | @endtask
107 | ```
108 |
109 |
110 | ### Setup
111 |
112 | Sometimes, you may need to execute arbitrary PHP code before running your Envoy tasks. You may use the `@setup` directive to define a block of PHP code that should execute before your tasks:
113 |
114 | ```php
115 | @setup
116 | $now = new DateTime;
117 | @endsetup
118 | ```
119 |
120 | If you need to require other PHP files before your task is executed, you may use the `@include` directive at the top of your `Envoy.blade.php` file:
121 |
122 | ```blade
123 | @include('vendor/autoload.php')
124 |
125 | @task('restart-queues')
126 | # ...
127 | @endtask
128 | ```
129 |
130 |
131 | ### Variables
132 |
133 | If needed, you may pass arguments to Envoy tasks by specifying them on the command line when invoking Envoy:
134 |
135 | ```shell
136 | php vendor/bin/envoy run deploy --branch=master
137 | ```
138 |
139 | You may access the options within your tasks using Blade's "echo" syntax. You may also define Blade `if` statements and loops within your tasks. For example, let's verify the presence of the `$branch` variable before executing the `git pull` command:
140 |
141 | ```blade
142 | @servers(['web' => ['user@192.168.1.1']])
143 |
144 | @task('deploy', ['on' => 'web'])
145 | cd /home/user/example.com
146 |
147 | @if ($branch)
148 | git pull origin {{ $branch }}
149 | @endif
150 |
151 | php artisan migrate --force
152 | @endtask
153 | ```
154 |
155 |
156 | ### Stories
157 |
158 | Stories group a set of tasks under a single, convenient name. For instance, a `deploy` story may run the `update-code` and `install-dependencies` tasks by listing the task names within its definition:
159 |
160 | ```blade
161 | @servers(['web' => ['user@192.168.1.1']])
162 |
163 | @story('deploy')
164 | update-code
165 | install-dependencies
166 | @endstory
167 |
168 | @task('update-code')
169 | cd /home/user/example.com
170 | git pull origin master
171 | @endtask
172 |
173 | @task('install-dependencies')
174 | cd /home/user/example.com
175 | composer install
176 | @endtask
177 | ```
178 |
179 | Once the story has been written, you may invoke it in the same way you would invoke a task:
180 |
181 | ```shell
182 | php vendor/bin/envoy run deploy
183 | ```
184 |
185 |
186 | ### Hooks
187 |
188 | When tasks and stories run, a number of hooks are executed. The hook types supported by Envoy are `@before`, `@after`, `@error`, `@success`, and `@finished`. All of the code in these hooks is interpreted as PHP and executed locally, not on the remote servers that your tasks interact with.
189 |
190 | You may define as many of each of these hooks as you like. They will be executed in the order that they appear in your Envoy script.
191 |
192 |
193 | #### `@before`
194 |
195 | Before each task execution, all of the `@before` hooks registered in your Envoy script will execute. The `@before` hooks receive the name of the task that will be executed:
196 |
197 | ```blade
198 | @before
199 | if ($task === 'deploy') {
200 | // ...
201 | }
202 | @endbefore
203 | ```
204 |
205 |
206 | #### `@after`
207 |
208 | After each task execution, all of the `@after` hooks registered in your Envoy script will execute. The `@after` hooks receive the name of the task that was executed:
209 |
210 | ```blade
211 | @after
212 | if ($task === 'deploy') {
213 | // ...
214 | }
215 | @endafter
216 | ```
217 |
218 |
219 | #### `@error`
220 |
221 | After every task failure (exits with a status code greater than `0`), all of the `@error` hooks registered in your Envoy script will execute. The `@error` hooks receive the name of the task that was executed:
222 |
223 | ```blade
224 | @error
225 | if ($task === 'deploy') {
226 | // ...
227 | }
228 | @enderror
229 | ```
230 |
231 |
232 | #### `@success`
233 |
234 | If all tasks have executed without errors, all of the `@success` hooks registered in your Envoy script will execute:
235 |
236 | ```blade
237 | @success
238 | // ...
239 | @endsuccess
240 | ```
241 |
242 |
243 | #### `@finished`
244 |
245 | After all tasks have been executed (regardless of exit status), all of the `@finished` hooks will be executed. The `@finished` hooks receive the status code of the completed task, which may be `null` or an `integer` greater than or equal to `0`:
246 |
247 | ```blade
248 | @finished
249 | if ($exitCode > 0) {
250 | // There were errors in one of the tasks...
251 | }
252 | @endfinished
253 | ```
254 |
255 |
256 | ## Running Tasks
257 |
258 | To run a task or story that is defined in your application's `Envoy.blade.php` file, execute Envoy's `run` command, passing the name of the task or story you would like to execute. Envoy will execute the task and display the output from your remote servers as the task is running:
259 |
260 | ```shell
261 | php vendor/bin/envoy run deploy
262 | ```
263 |
264 |
265 | ### Confirming Task Execution
266 |
267 | If you would like to be prompted for confirmation before running a given task on your servers, you should add the `confirm` directive to your task declaration. This option is particularly useful for destructive operations:
268 |
269 | ```blade
270 | @task('deploy', ['on' => 'web', 'confirm' => true])
271 | cd /home/user/example.com
272 | git pull origin {{ $branch }}
273 | php artisan migrate
274 | @endtask
275 | ```
276 |
277 |
278 | ## Notifications
279 |
280 |
281 | ### Slack
282 |
283 | Envoy supports sending notifications to [Slack](https://slack.com) after each task is executed. The `@slack` directive accepts a Slack hook URL and a channel / user name. You may retrieve your webhook URL by creating an "Incoming WebHooks" integration in your Slack control panel.
284 |
285 | You should pass the entire webhook URL as the first argument given to the `@slack` directive. The second argument given to the `@slack` directive should be a channel name (`#channel`) or a user name (`@user`):
286 |
287 | ```blade
288 | @finished
289 | @slack('webhook-url', '#bots')
290 | @endfinished
291 | ```
292 |
293 | By default, Envoy notifications will send a message to the notification channel describing the task that was executed. However, you may overwrite this message with your own custom message by passing a third argument to the `@slack` directive:
294 |
295 | ```blade
296 | @finished
297 | @slack('webhook-url', '#bots', 'Hello, Slack.')
298 | @endfinished
299 | ```
300 |
301 |
302 | ### Discord
303 |
304 | Envoy also supports sending notifications to [Discord](https://discord.com) after each task is executed. The `@discord` directive accepts a Discord hook URL and a message. You may retrieve your webhook URL by creating a "Webhook" in your Server Settings and choosing which channel the webhook should post to. You should pass the entire Webhook URL into the `@discord` directive:
305 |
306 | ```blade
307 | @finished
308 | @discord('discord-webhook-url')
309 | @endfinished
310 | ```
311 |
312 |
313 | ### Telegram
314 |
315 | Envoy also supports sending notifications to [Telegram](https://telegram.org) after each task is executed. The `@telegram` directive accepts a Telegram Bot ID and a Chat ID. You may retrieve your Bot ID by creating a new bot using [BotFather](https://t.me/botfather). You can retrieve a valid Chat ID using [@username_to_id_bot](https://t.me/username_to_id_bot). You should pass the entire Bot ID and Chat ID into the `@telegram` directive:
316 |
317 | ```blade
318 | @finished
319 | @telegram('bot-id','chat-id')
320 | @endfinished
321 | ```
322 |
323 |
324 | ### Microsoft Teams
325 |
326 | Envoy also supports sending notifications to [Microsoft Teams](https://www.microsoft.com/en-us/microsoft-teams) after each task is executed. The `@microsoftTeams` directive accepts a Teams Webhook (required), a message, theme color (success, info, warning, error), and an array of options. You may retrieve your Teams Webook by creating a new [incoming webhook](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook). The Teams API has many other attributes to customize your message box like title, summary, and sections. You can find more information on the [Microsoft Teams documentation](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#example-of-connector-message). You should pass the entire Webhook URL into the `@microsoftTeams` directive:
327 |
328 | ```blade
329 | @finished
330 | @microsoftTeams('webhook-url')
331 | @endfinished
332 | ```
333 |
--------------------------------------------------------------------------------
/errors.md:
--------------------------------------------------------------------------------
1 | # Error Handling
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [The Exception Handler](#the-exception-handler)
6 | - [Reporting Exceptions](#reporting-exceptions)
7 | - [Ignoring Exceptions By Type](#ignoring-exceptions-by-type)
8 | - [Rendering Exceptions](#rendering-exceptions)
9 | - [Reportable & Renderable Exceptions](#renderable-exceptions)
10 | - [HTTP Exceptions](#http-exceptions)
11 | - [Custom HTTP Error Pages](#custom-http-error-pages)
12 |
13 |
14 | ## Introduction
15 |
16 | When you start a new Laravel project, error and exception handling is already configured for you. The `App\Exceptions\Handler` class is where all exceptions thrown by your application are logged and then rendered to the user. We'll dive deeper into this class throughout this documentation.
17 |
18 |
19 | ## Configuration
20 |
21 | The `debug` option in your `config/app.php` configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the `APP_DEBUG` environment variable, which is stored in your `.env` file.
22 |
23 | During local development, you should set the `APP_DEBUG` environment variable to `true`. **In your production environment, this value should always be `false`. If the value is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.**
24 |
25 |
26 | ## The Exception Handler
27 |
28 |
29 | ### Reporting Exceptions
30 |
31 | All exceptions are handled by the `App\Exceptions\Handler` class. This class contains a `register` method where you may register custom exception reporting and rendering callbacks. We'll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like [Flare](https://flareapp.io), [Bugsnag](https://bugsnag.com) or [Sentry](https://github.com/getsentry/sentry-laravel). By default, exceptions will be logged based on your [logging](/docs/{{version}}/logging) configuration. However, you are free to log exceptions however you wish.
32 |
33 | For example, if you need to report different types of exceptions in different ways, you may use the `reportable` method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
34 |
35 | use App\Exceptions\InvalidOrderException;
36 |
37 | /**
38 | * Register the exception handling callbacks for the application.
39 | *
40 | * @return void
41 | */
42 | public function register()
43 | {
44 | $this->reportable(function (InvalidOrderException $e) {
45 | //
46 | });
47 | }
48 |
49 | When you register a custom exception reporting callback using the `reportable` method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the `stop` method when defining your reporting callback or return `false` from the callback:
50 |
51 | $this->reportable(function (InvalidOrderException $e) {
52 | //
53 | })->stop();
54 |
55 | $this->reportable(function (InvalidOrderException $e) {
56 | return false;
57 | });
58 |
59 | > {tip} To customize the exception reporting for a given exception, you may also utilize [reportable exceptions](/docs/{{version}}/errors#renderable-exceptions).
60 |
61 |
62 | #### Global Log Context
63 |
64 | If available, Laravel automatically adds the current user's ID to every exception's log message as contextual data. You may define your own global contextual data by overriding the `context` method of your application's `App\Exceptions\Handler` class. This information will be included in every exception's log message written by your application:
65 |
66 | /**
67 | * Get the default context variables for logging.
68 | *
69 | * @return array
70 | */
71 | protected function context()
72 | {
73 | return array_merge(parent::context(), [
74 | 'foo' => 'bar',
75 | ]);
76 | }
77 |
78 |
79 | #### Exception Log Context
80 |
81 | While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a `context` method on one of your application's custom exceptions, you may specify any data relevant to that exception that should be added to the exception's log entry:
82 |
83 | $this->orderId];
101 | }
102 | }
103 |
104 |
105 | #### The `report` Helper
106 |
107 | Sometimes you may need to report an exception but continue handling the current request. The `report` helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
108 |
109 | public function isValid($value)
110 | {
111 | try {
112 | // Validate the value...
113 | } catch (Throwable $e) {
114 | report($e);
115 |
116 | return false;
117 | }
118 | }
119 |
120 |
121 | ### Ignoring Exceptions By Type
122 |
123 | When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application's exception handler contains a `$dontReport` property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
124 |
125 | use App\Exceptions\InvalidOrderException;
126 |
127 | /**
128 | * A list of the exception types that should not be reported.
129 | *
130 | * @var array
131 | */
132 | protected $dontReport = [
133 | InvalidOrderException::class,
134 | ];
135 |
136 | > {tip} Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP "not found" errors or 419 HTTP responses generated by invalid CSRF tokens.
137 |
138 |
139 | ### Rendering Exceptions
140 |
141 | By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the `renderable` method of your exception handler.
142 |
143 | The closure passed to the `renderable` method should return an instance of `Illuminate\Http\Response`, which may be generated via the `response` helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
144 |
145 | use App\Exceptions\InvalidOrderException;
146 |
147 | /**
148 | * Register the exception handling callbacks for the application.
149 | *
150 | * @return void
151 | */
152 | public function register()
153 | {
154 | $this->renderable(function (InvalidOrderException $e, $request) {
155 | return response()->view('errors.invalid-order', [], 500);
156 | });
157 | }
158 |
159 | You may also use the `renderable` method to override the rendering behavior for built-in Laravel or Symfony exceptions such as `NotFoundHttpException`. If the closure given to the `renderable` method does not return a value, Laravel's default exception rendering will be utilized:
160 |
161 | use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
162 |
163 | /**
164 | * Register the exception handling callbacks for the application.
165 | *
166 | * @return void
167 | */
168 | public function register()
169 | {
170 | $this->renderable(function (NotFoundHttpException $e, $request) {
171 | if ($request->is('api/*')) {
172 | return response()->json([
173 | 'message' => 'Record not found.'
174 | ], 404);
175 | }
176 | });
177 | }
178 |
179 |
180 | ### Reportable & Renderable Exceptions
181 |
182 | Instead of type-checking exceptions in the exception handler's `register` method, you may define `report` and `render` methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
183 |
184 | {tip} You may type-hint any required dependencies of the `report` method and they will automatically be injected into the method by Laravel's [service container](/docs/{{version}}/container).
244 |
245 |
246 | ## HTTP Exceptions
247 |
248 | Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the `abort` helper:
249 |
250 | abort(404);
251 |
252 |
253 | ### Custom HTTP Error Pages
254 |
255 | Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a `resources/views/errors/404.blade.php` view template. This view will be rendered on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The `Symfony\Component\HttpKernel\Exception\HttpException` instance raised by the `abort` function will be passed to the view as an `$exception` variable:
256 |
257 | {{ $exception->getMessage() }}
258 |
259 | You may publish Laravel's default error page templates using the `vendor:publish` Artisan command. Once the templates have been published, you may customize them to your liking:
260 |
261 | ```shell
262 | php artisan vendor:publish --tag=laravel-errors
263 | ```
264 |
265 |
266 | #### Fallback HTTP Error Pages
267 |
268 | You may also define a "fallback" error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a `4xx.blade.php` template and a `5xx.blade.php` template in your application's `resources/views/errors` directory.
269 |
--------------------------------------------------------------------------------
/hashing.md:
--------------------------------------------------------------------------------
1 | # Hashing
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [Basic Usage](#basic-usage)
6 | - [Hashing Passwords](#hashing-passwords)
7 | - [Verifying That A Password Matches A Hash](#verifying-that-a-password-matches-a-hash)
8 | - [Determining If A Password Needs To Be Rehashed](#determining-if-a-password-needs-to-be-rehashed)
9 |
10 |
11 | ## Introduction
12 |
13 | The Laravel `Hash` [facade](/docs/{{version}}/facades) provides secure Bcrypt and Argon2 hashing for storing user passwords. If you are using one of the [Laravel application starter kits](/docs/{{version}}/starter-kits), Bcrypt will be used for registration and authentication by default.
14 |
15 | Bcrypt is a great choice for hashing passwords because its "work factor" is adjustable, which means that the time it takes to generate a hash can be increased as hardware power increases. When hashing passwords, slow is good. The longer an algorithm takes to hash a password, the longer it takes malicious users to generate "rainbow tables" of all possible string hash values that may be used in brute force attacks against applications.
16 |
17 |
18 | ## Configuration
19 |
20 | The default hashing driver for your application is configured in your application's `config/hashing.php` configuration file. There are currently several supported drivers: [Bcrypt](https://en.wikipedia.org/wiki/Bcrypt) and [Argon2](https://en.wikipedia.org/wiki/Argon2) (Argon2i and Argon2id variants).
21 |
22 |
23 | ## Basic Usage
24 |
25 |
26 | ### Hashing Passwords
27 |
28 | You may hash a password by calling the `make` method on the `Hash` facade:
29 |
30 | user()->fill([
51 | 'password' => Hash::make($request->newPassword)
52 | ])->save();
53 | }
54 | }
55 |
56 |
57 | #### Adjusting The Bcrypt Work Factor
58 |
59 | If you are using the Bcrypt algorithm, the `make` method allows you to manage the work factor of the algorithm using the `rounds` option; however, the default work factor managed by Laravel is acceptable for most applications:
60 |
61 | $hashed = Hash::make('password', [
62 | 'rounds' => 12,
63 | ]);
64 |
65 |
66 | #### Adjusting The Argon2 Work Factor
67 |
68 | If you are using the Argon2 algorithm, the `make` method allows you to manage the work factor of the algorithm using the `memory`, `time`, and `threads` options; however, the default values managed by Laravel are acceptable for most applications:
69 |
70 | $hashed = Hash::make('password', [
71 | 'memory' => 1024,
72 | 'time' => 2,
73 | 'threads' => 2,
74 | ]);
75 |
76 | > {tip} For more information on these options, please refer to the [official PHP documentation regarding Argon hashing](https://secure.php.net/manual/en/function.password-hash.php).
77 |
78 |
79 | ### Verifying That A Password Matches A Hash
80 |
81 | The `check` method provided by the `Hash` facade allows you to verify that a given plain-text string corresponds to a given hash:
82 |
83 | if (Hash::check('plain-text', $hashedPassword)) {
84 | // The passwords match...
85 | }
86 |
87 |
88 | ### Determining If A Password Needs To Be Rehashed
89 |
90 | The `needsRehash` method provided by the `Hash` facade allows you to determine if the work factor used by the hasher has changed since the password was hashed. Some applications choose to perform this check during the application's authentication process:
91 |
92 | if (Hash::needsRehash($hashed)) {
93 | $hashed = Hash::make('plain-text');
94 | }
95 |
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) Taylor Otwell
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
--------------------------------------------------------------------------------
/lifecycle.md:
--------------------------------------------------------------------------------
1 | # Request Lifecycle
2 |
3 | - [Introduction](#introduction)
4 | - [Lifecycle Overview](#lifecycle-overview)
5 | - [First Steps](#first-steps)
6 | - [HTTP / Console Kernels](#http-console-kernels)
7 | - [Service Providers](#service-providers)
8 | - [Routing](#routing)
9 | - [Finishing Up](#finishing-up)
10 | - [Focus On Service Providers](#focus-on-service-providers)
11 |
12 |
13 | ## Introduction
14 |
15 | When using any tool in the "real world", you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them.
16 |
17 | The goal of this document is to give you a good, high-level overview of how the Laravel framework works. By getting to know the overall framework better, everything feels less "magical" and you will be more confident building your applications. If you don't understand all of the terms right away, don't lose heart! Just try to get a basic grasp of what is going on, and your knowledge will grow as you explore other sections of the documentation.
18 |
19 |
20 | ## Lifecycle Overview
21 |
22 |
23 | ### First Steps
24 |
25 | The entry point for all requests to a Laravel application is the `public/index.php` file. All requests are directed to this file by your web server (Apache / Nginx) configuration. The `index.php` file doesn't contain much code. Rather, it is a starting point for loading the rest of the framework.
26 |
27 | The `index.php` file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from `bootstrap/app.php`. The first action taken by Laravel itself is to create an instance of the application / [service container](/docs/{{version}}/container).
28 |
29 |
30 | ### HTTP / Console Kernels
31 |
32 | Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let's just focus on the HTTP kernel, which is located in `app/Http/Kernel.php`.
33 |
34 | The HTTP kernel extends the `Illuminate\Foundation\Http\Kernel` class, which defines an array of `bootstrappers` that will be run before the request is executed. These bootstrappers configure error handling, configure logging, [detect the application environment](/docs/{{version}}/configuration#environment-configuration), and perform other tasks that need to be done before the request is actually handled. Typically, these classes handle internal Laravel configuration that you do not need to worry about.
35 |
36 | The HTTP kernel also defines a list of HTTP [middleware](/docs/{{version}}/middleware) that all requests must pass through before being handled by the application. These middleware handle reading and writing the [HTTP session](/docs/{{version}}/session), determining if the application is in maintenance mode, [verifying the CSRF token](/docs/{{version}}/csrf), and more. We'll talk more about these soon.
37 |
38 | The method signature for the HTTP kernel's `handle` method is quite simple: it receives a `Request` and returns a `Response`. Think of the kernel as being a big black box that represents your entire application. Feed it HTTP requests and it will return HTTP responses.
39 |
40 |
41 | ### Service Providers
42 |
43 | One of the most important kernel bootstrapping actions is loading the [service providers](/docs/{{version}}/providers) for your application. All of the service providers for the application are configured in the `config/app.php` configuration file's `providers` array.
44 |
45 | Laravel will iterate through this list of providers and instantiate each of them. After instantiating the providers, the `register` method will be called on all of the providers. Then, once all of the providers have been registered, the `boot` method will be called on each provider. This is so service providers may depend on every container binding being registered and available by the time their `boot` method is executed.
46 |
47 | Service providers are responsible for bootstrapping all of the framework's various components, such as the database, queue, validation, and routing components. Essentially every major feature offered by Laravel is bootstrapped and configured by a service provider. Since they bootstrap and configure so many features offered by the framework, service providers are the most important aspect of the entire Laravel bootstrap process.
48 |
49 |
50 | ### Routing
51 |
52 | One of the most important service providers in your application is the `App\Providers\RouteServiceProvider`. This service provider loads the route files contained within your application's `routes` directory. Go ahead, crack open the `RouteServiceProvider` code and take a look at how it works!
53 |
54 | Once the application has been bootstrapped and all service providers have been registered, the `Request` will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware.
55 |
56 | Middleware provide a convenient mechanism for filtering or examining HTTP requests entering your application. For example, Laravel includes a middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Some middleware are assigned to all routes within the application, like those defined in the `$middleware` property of your HTTP kernel, while some are only assigned to specific routes or route groups. You can learn more about middleware by reading the complete [middleware documentation](/docs/{{version}}/middleware).
57 |
58 | If the request passes through all of the matched route's assigned middleware, the route or controller method will be executed and the response returned by the route or controller method will be sent back through the route's chain of middleware.
59 |
60 |
61 | ### Finishing Up
62 |
63 | Once the route or controller method returns a response, the response will travel back outward through the route's middleware, giving the application a chance to modify or examine the outgoing response.
64 |
65 | Finally, once the response travels back through the middleware, the HTTP kernel's `handle` method returns the response object and the `index.php` file calls the `send` method on the returned response. The `send` method sends the response content to the user's web browser. We've finished our journey through the entire Laravel request lifecycle!
66 |
67 |
68 | ## Focus On Service Providers
69 |
70 | Service providers are truly the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application. It's really that simple!
71 |
72 | Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Your application's default service providers are stored in the `app/Providers` directory.
73 |
74 | By default, the `AppServiceProvider` is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. For large applications, you may wish to create several service providers, each with more granular bootstrapping for specific services used by your application.
75 |
--------------------------------------------------------------------------------
/localization.md:
--------------------------------------------------------------------------------
1 | # Localization
2 |
3 | - [Introduction](#introduction)
4 | - [Configuring The Locale](#configuring-the-locale)
5 | - [Defining Translation Strings](#defining-translation-strings)
6 | - [Using Short Keys](#using-short-keys)
7 | - [Using Translation Strings As Keys](#using-translation-strings-as-keys)
8 | - [Retrieving Translation Strings](#retrieving-translation-strings)
9 | - [Replacing Parameters In Translation Strings](#replacing-parameters-in-translation-strings)
10 | - [Pluralization](#pluralization)
11 | - [Overriding Package Language Files](#overriding-package-language-files)
12 |
13 |
14 | ## Introduction
15 |
16 | Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.
17 |
18 | Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the `lang` directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages:
19 |
20 | /lang
21 | /en
22 | messages.php
23 | /es
24 | messages.php
25 |
26 | Or, translation strings may be defined within JSON files that are placed within the `lang` directory. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for application's that have a large number of translatable strings:
27 |
28 | /lang
29 | en.json
30 | es.json
31 |
32 | We'll discuss each approach to managing translation strings within this documentation.
33 |
34 |
35 | ### Configuring The Locale
36 |
37 | The default language for your application is stored in the `config/app.php` configuration file's `locale` configuration option. You are free to modify this value to suit the needs of your application.
38 |
39 | You may modify the default language for a single HTTP request at runtime using the `setLocale` method provided by the `App` facade:
40 |
41 | use Illuminate\Support\Facades\App;
42 |
43 | Route::get('/greeting/{locale}', function ($locale) {
44 | if (! in_array($locale, ['en', 'es', 'fr'])) {
45 | abort(400);
46 | }
47 |
48 | App::setLocale($locale);
49 |
50 | //
51 | });
52 |
53 | You may configure a "fallback language", which will be used when the active language does not contain a given translation string. Like the default language, the fallback language is also configured in the `config/app.php` configuration file:
54 |
55 | 'fallback_locale' => 'en',
56 |
57 |
58 | #### Determining The Current Locale
59 |
60 | You may use the `currentLocale` and `isLocale` methods on the `App` facade to determine the current locale or check if the locale is a given value:
61 |
62 | use Illuminate\Support\Facades\App;
63 |
64 | $locale = App::currentLocale();
65 |
66 | if (App::isLocale('en')) {
67 | //
68 | }
69 |
70 |
71 | ## Defining Translation Strings
72 |
73 |
74 | ### Using Short Keys
75 |
76 | Typically, translation strings are stored in files within the `lang` directory. Within this directory, there should be a subdirectory for each language supported by your application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages:
77 |
78 | /lang
79 | /en
80 | messages.php
81 | /es
82 | messages.php
83 |
84 | All language files return an array of keyed strings. For example:
85 |
86 | 'Welcome to our application!',
92 | ];
93 |
94 | > {note} For languages that differ by territory, you should name the language directories according to the ISO 15897. For example, "en_GB" should be used for British English rather than "en-gb".
95 |
96 |
97 | ### Using Translation Strings As Keys
98 |
99 | For applications with a large number of translatable strings, defining every string with a "short key" can become confusing when referencing the keys in your views and it is cumbersome to continually invent keys for every translation string supported by your application.
100 |
101 | For this reason, Laravel also provides support for defining translation strings using the "default" translation of the string as the key. Translation files that use translation strings as keys are stored as JSON files in the `lang` directory. For example, if your application has a Spanish translation, you should create a `lang/es.json` file:
102 |
103 | ```json
104 | {
105 | "I love programming.": "Me encanta programar."
106 | }
107 | ```
108 |
109 | #### Key / File Conflicts
110 |
111 | You should not define translation string keys that conflict with other translation filenames. For example, translating `__('Action')` for the "NL" locale while a `nl/action.php` file exists but a `nl.json` file does not exist will result in the translator returning the contents of `nl/action.php`.
112 |
113 |
114 | ## Retrieving Translation Strings
115 |
116 | You may retrieve translation strings from your language files using the `__` helper function. If you are using "short keys" to define your translation strings, you should pass the file that contains the key and the key itself to the `__` function using "dot" syntax. For example, let's retrieve the `welcome` translation string from the `lang/en/messages.php` language file:
117 |
118 | echo __('messages.welcome');
119 |
120 | If the specified translation string does not exist, the `__` function will return the translation string key. So, using the example above, the `__` function would return `messages.welcome` if the translation string does not exist.
121 |
122 | If you are using your [default translation strings as your translation keys](#using-translation-strings-as-keys), you should pass the default translation of your string to the `__` function;
123 |
124 | echo __('I love programming.');
125 |
126 | Again, if the translation string does not exist, the `__` function will return the translation string key that it was given.
127 |
128 | If you are using the [Blade templating engine](/docs/{{version}}/blade), you may use the `{{ }}` echo syntax to display the translation string:
129 |
130 | {{ __('messages.welcome') }}
131 |
132 |
133 | ### Replacing Parameters In Translation Strings
134 |
135 | If you wish, you may define placeholders in your translation strings. All placeholders are prefixed with a `:`. For example, you may define a welcome message with a placeholder name:
136 |
137 | 'welcome' => 'Welcome, :name',
138 |
139 | To replace the placeholders when retrieving a translation string, you may pass an array of replacements as the second argument to the `__` function:
140 |
141 | echo __('messages.welcome', ['name' => 'dayle']);
142 |
143 | If your placeholder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly:
144 |
145 | 'welcome' => 'Welcome, :NAME', // Welcome, DAYLE
146 | 'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle
147 |
148 |
149 | ### Pluralization
150 |
151 | Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization; however, Laravel can help you translate strings differently based on pluralization rules that you define. Using a `|` character, you may distinguish singular and plural forms of a string:
152 |
153 | 'apples' => 'There is one apple|There are many apples',
154 |
155 | Of course, pluralization is also supported when using [translation strings as keys](#using-translation-strings-as-keys):
156 |
157 | ```json
158 | {
159 | "There is one apple|There are many apples": "Hay una manzana|Hay muchas manzanas"
160 | }
161 | ```
162 |
163 | You may even create more complex pluralization rules which specify translation strings for multiple ranges of values:
164 |
165 | 'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many',
166 |
167 | After defining a translation string that has pluralization options, you may use the `trans_choice` function to retrieve the line for a given "count". In this example, since the count is greater than one, the plural form of the translation string is returned:
168 |
169 | echo trans_choice('messages.apples', 10);
170 |
171 | You may also define placeholder attributes in pluralization strings. These placeholders may be replaced by passing an array as the third argument to the `trans_choice` function:
172 |
173 | 'minutes_ago' => '{1} :value minute ago|[2,*] :value minutes ago',
174 |
175 | echo trans_choice('time.minutes_ago', 5, ['value' => 5]);
176 |
177 | If you would like to display the integer value that was passed to the `trans_choice` function, you may use the built-in `:count` placeholder:
178 |
179 | 'apples' => '{0} There are none|{1} There is one|[2,*] There are :count',
180 |
181 |
182 | ## Overriding Package Language Files
183 |
184 | Some packages may ship with their own language files. Instead of changing the package's core files to tweak these lines, you may override them by placing files in the `lang/vendor/{package}/{locale}` directory.
185 |
186 | So, for example, if you need to override the English translation strings in `messages.php` for a package named `skyrim/hearthfire`, you should place a language file at: `lang/vendor/hearthfire/en/messages.php`. Within this file, you should only define the translation strings you wish to override. Any translation strings you don't override will still be loaded from the package's original language files.
187 |
--------------------------------------------------------------------------------
/middleware.md:
--------------------------------------------------------------------------------
1 | # الكائن الوسيط
2 |
3 | - [المقدمة](#introduction)
4 | - [تعريف الكائن الوسيط](#defining-middleware)
5 | - [تسجيل الكائن الوسيط](#registering-middleware)
6 | - [الكائن الوسيط العام](#global-middleware)
7 | - [تعيين الكائن الوسيط للمسارات](#assigning-middleware-to-routes)
8 | - [مجموعات الكائن الوسيط](#middleware-groups)
9 | - [ترتيب الكائن الوسيط](#sorting-middleware)
10 | - [متغيرات الكائن الوسيط](#middleware-parameters)
11 | - [الكائن الوسيط القابل للإنهاء](#terminable-middleware)
12 |
13 |
14 | ## المقدمة
15 | يؤمن الكائن الوسيط اّلية مناسبة لفحص وفلترة طلبات بروتوكول HTTP
16 | مثال: يتحقق الكائن الوسيط ضمن لارافل من المستخدم إذا كان مسجل ضمن الموقع أو غير مسجل
17 | إذا كان غير مسجل يحوله إلى صفحة تسجيل الدخول إذا كان مسجل يسمح له بالدخول إلى الموقع
18 |
19 | يتوضع الكائن الوسيط ضمن مجلد `app/Http/Middleware`
20 | يوجد كائنات لتنفيذ المهام المتنوعة إلى جانب كائن التحقق من تسجيل الدخول والحماية من ثغرة CSRF (Cross-Site Request Forgery)
21 |
22 |
23 | ## تعريف الكائن الوسيط
24 |
25 | لإنشاء كائن وسيط نستخدم الأمر `make:middleware`
26 |
27 | ```shell
28 | php artisan make:middleware EnsureTokenIsValid
29 | ```
30 |
31 |
32 | أنشأ الأمر السابق صف`EnsureTokenIsValid` ضمن المجلد`app/Http/Middleware`
33 | هذا الكائن الوسيط يسمح بالوصول إلى المسار في حال تساوي`token` المدخلة مع القيمة الموجودة غير ذلك يقوم بتحويل المستخدم إلى الصفحة الرئيسية`home`
34 |
35 | input('token') !== 'my-secret-token') {
53 | return redirect('home');
54 | }
55 |
56 | return $next($request);
57 | }
58 | }
59 |
60 | كما ترى إذا كان العّلام المُعطى لا يماثل العّلام السري سيقوم الكائن الوسيط بتحويل المستخدم للصفحة الرئيسية غير ذلك يسمح للمستخدم بالدخول إلى صفحات التطبيق نقوم بنداء `$next` و ضمنها `$request`
61 |
62 | من الأفضل تصور الكائن الوسيط كسلسلة طبقات تمر عبرها طلبات HTTP كل طبقة تفحص طلب HTTP و حتى رفضه داخليا
63 |
64 |
65 |
66 |
67 | #### الكائن الوسيط والاستجابة
68 | ينفذ الكائن الوسيط المهام قبل وبعد تمرير الطلب أعمق بالتطبيق
69 | في المثال التالي سيقوم الكائن الوسيط بتنفيذ المهمة قبل معالجة الطلب من قبل التطبيق
70 |
71 |
108 | ## تسجيل الكائن الوسيط
109 |
110 | ### الكائن الوسيط العام
111 |
112 | إذا أردت تشغيل الكائن الوسيط في كل طلب HTTP ضع صف الكائن الوسيط في الخاصية`$middleware` في الصف `app/Http/Kernel.php`
113 |
114 |
115 | ### تعيين الكائن الوسيط للمسارات
116 | إذا أردت تعيين الكائن الوسيط لمسارات مخصصة يجب تعيين مفتاح للكائن الوسيط ضمن الملف `app/Http/Kernel.php`
117 | افتراضيا تحوي الخاصية`$routeMiddleware` في هذا الصف الكائن الوسيط المضمن في لارافل
118 | يمكنك إضافة الوسيط الخاص بك وتعيين مفتاح خاص به
119 |
120 | // Within App\Http\Kernel class...
121 |
122 | protected $routeMiddleware = [
123 | 'auth' => \App\Http\Middleware\Authenticate::class,
124 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
125 | 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
126 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
127 | 'can' => \Illuminate\Auth\Middleware\Authorize::class,
128 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
129 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
130 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
131 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
132 | ];
133 |
134 | الكائن الوسيط الأول تم تعريفه لنستخدم الطريقة`middleware` في تعيين كائن وسيط للمسار
135 |
136 | Route::get('/profile', function () {
137 | //
138 | })->middleware('auth');
139 |
140 |
141 | يمكن تعيين عدة كائنات وسيطة للمسار بتمرير مصفوفة بأسماء الكائنات الوسيطة للطريقة `middleware`
142 |
143 | Route::get('/', function () {
144 | //
145 | })->middleware(['first', 'second']);
146 |
147 | عند تعيين الكائن الوسيط يمكنك تمرير الاسم الكامل للصف
148 |
149 | use App\Http\Middleware\EnsureTokenIsValid;
150 |
151 | Route::get('/profile', function () {
152 | //
153 | })->middleware(EnsureTokenIsValid::class);
154 |
155 |
156 | #### استثناء أو استبعاد الكائن الوسيط
157 |
158 | عند تعيين كائن وسيط لمجموعة مسارات عادة نحتاج استثناء كائن وسيط من أحد المسارات ضمن المجموعة يمكن انجاز ذلك باستخدام الطريقة `withoutMiddleware’
159 |
160 | use App\Http\Middleware\EnsureTokenIsValid;
161 |
162 | Route::middleware([EnsureTokenIsValid::class])->group(function () {
163 | Route::get('/', function () {
164 | //
165 | });
166 |
167 | Route::get('/profile', function () {
168 | //
169 | })->withoutMiddleware([EnsureTokenIsValid::class]);
170 | });
171 |
172 |
173 | يمكن استبعاد مجموعة كائنات وسيطة معطاة من مجموعة مدخلة للمسار الوجهة
174 |
175 | use App\Http\Middleware\EnsureTokenIsValid;
176 |
177 | Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
178 | Route::get('/profile', function () {
179 | //
180 | });
181 | });
182 |
183 |
184 | الطريقة `withoutMiddleware` تحذف مسار الكائن الوسيط ولا تقبل [global middleware](#global-middleware)
185 |
186 |
187 |
188 | ### مجموعات الكائن الوسيط
189 |
190 | إذا أردت عمل مجموعة كائن وسيط تحت مفتاح واحد لسهولة تعيينهم للمسارات يمكن انجاز ذلك باستخدام الخاصية `$middlewareGroups` ضمن الصف HTTP kernel
191 |
192 | يأتي مع لارافل مجموعات كائن وسيط`web` و`api` تحوي كائن وسيط يُطبق على مسارات `api` و`api`
193 | هذه المجموعات تُطبق بشكل اّلي بواسطة مقدم الخدمة `App\Providers\RouteServiceProvider للمسارات `api` و `api`
194 |
195 |
196 |
197 | /**
198 | * The application's route middleware groups.
199 | *
200 | * @var array
201 | */
202 | protected $middlewareGroups = [
203 | 'web' => [
204 | \App\Http\Middleware\EncryptCookies::class,
205 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
206 | \Illuminate\Session\Middleware\StartSession::class,
207 | // \Illuminate\Session\Middleware\AuthenticateSession::class,
208 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
209 | \App\Http\Middleware\VerifyCsrfToken::class,
210 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
211 | ],
212 |
213 | 'api' => [
214 | 'throttle:api',
215 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
216 | ],
217 | ];
218 |
219 | مجموعات الكائن الوسيط تستخدم نفس بناء الكود للكائن الوسيط الوحيد
220 |
221 |
222 | Route::get('/', function () {
223 | //
224 | })->middleware('web');
225 |
226 | Route::middleware(['web'])->group(function () {
227 | //
228 | });
229 |
230 |
231 |
232 | ### ترتيب الكائن الوسيط
233 |
234 | نادراً ما نحتاج لتنفيذ الوسيط بترتيب معين لا نملك سيطرة على هذا الترتيب عند تعيين المسار
235 | في هذه الحالة نحدد أولوية للكائن باستخدام الخاصية`$middlewarePriority` في الملف `app/Http/Kernel.php`
236 | إذا لم تكن موجودة ضمن الملف يمكن وضع الكود الافتراضي في الملف
237 |
238 | /**
239 | * The priority-sorted list of middleware.
240 | *
241 | * This forces non-global middleware to always be in the given order.
242 | *
243 | * @var string[]
244 | */
245 | protected $middlewarePriority = [
246 | \Illuminate\Cookie\Middleware\EncryptCookies::class,
247 | \Illuminate\Session\Middleware\StartSession::class,
248 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
249 | \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
250 | \Illuminate\Routing\Middleware\ThrottleRequests::class,
251 | \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
252 | \Illuminate\Session\Middleware\AuthenticateSession::class,
253 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
254 | \Illuminate\Auth\Middleware\Authorize::class,
255 | ];
256 |
257 |
258 | ## متغيرات الكائن الوسيط
259 |
260 | يمكن أن يستقبل الوسيط متغيرات إضافية مثلاً عندما نحتاج لنتحقق من مستخدم مسجل إذا كان لديه وظيفة أو دور "role"
261 | ننشئ وسيط EnsureUserHasRole يستقبل اسم الوظيفة كمتغير إضافي
262 | سيتم تمرير المتغيرات بعد المتغير`$next`
263 |
264 | user()->hasRole($role)) {
283 | // Redirect...
284 | }
285 |
286 | return $next($request);
287 | }
288 |
289 | }
290 |
291 |
292 | تحديد متغيرات الوسيط عند تعريف المسار بفصل اسم الوسيط و المتغير باستخدام `:` في حال وجود عدة متغيرات نستخدم الفواصل
293 |
294 | Route::put('/post/{id}', function ($id) {
295 | //
296 | })->middleware('role:editor');
297 |
298 |
299 | ## الوسيط القابل للإنهاء
300 | أحيانا يحتاج الوسيط للقيام بعمل ما قبل أن تُرسل استجابة HTTP إلى المتصفح
301 | إذا عرفت الطريقة `terminate` في الوسيط ومخدم الويب الذي يستخدم FastCGI سيتم نداء الطريقة بشكل اّلي يعد إرسال الاستجابة للمتصفح
302 |
303 | app->singleton(TerminatingMiddleware::class);
353 | }
354 |
--------------------------------------------------------------------------------
/passwords.md:
--------------------------------------------------------------------------------
1 | # Resetting Passwords
2 |
3 | - [Introduction](#introduction)
4 | - [Model Preparation](#model-preparation)
5 | - [Database Preparation](#database-preparation)
6 | - [Configuring Trusted Hosts](#configuring-trusted-hosts)
7 | - [Routing](#routing)
8 | - [Requesting The Password Reset Link](#requesting-the-password-reset-link)
9 | - [Resetting The Password](#resetting-the-password)
10 | - [Deleting Expired Tokens](#deleting-expired-tokens)
11 | - [Customization](#password-customization)
12 |
13 |
14 | ## Introduction
15 |
16 | Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this by hand for every application you create, Laravel provides convenient services for sending password reset links and secure resetting passwords.
17 |
18 | > {tip} Want to get started fast? Install a Laravel [application starter kit](/docs/{{version}}/starter-kits) in a fresh Laravel application. Laravel's starter kits will take care of scaffolding your entire authentication system, including resetting forgotten passwords.
19 |
20 |
21 | ### Model Preparation
22 |
23 | Before using the password reset features of Laravel, your application's `App\Models\User` model must use the `Illuminate\Notifications\Notifiable` trait. Typically, this trait is already included on the default `App\Models\User` model that is created with new Laravel applications.
24 |
25 | Next, verify that your `App\Models\User` model implements the `Illuminate\Contracts\Auth\CanResetPassword` contract. The `App\Models\User` model included with the framework already implements this interface, and uses the `Illuminate\Auth\Passwords\CanResetPassword` trait to include the methods needed to implement the interface.
26 |
27 |
28 | ### Database Preparation
29 |
30 | A table must be created to store your application's password reset tokens. The migration for this table is included in the default Laravel application, so you only need to migrate your database to create this table:
31 |
32 | ```shell
33 | php artisan migrate
34 | ```
35 |
36 |
37 | ### Configuring Trusted Hosts
38 |
39 | By default, Laravel will respond to all requests it receives regardless of the content of the HTTP request's `Host` header. In addition, the `Host` header's value will be used when generating absolute URLs to your application during a web request.
40 |
41 | Typically, you should configure your web server, such as Nginx or Apache, to only send requests to your application that match a given host name. However, if you do not have the ability to customize your web server directly and need to instruct Laravel to only respond to certain host names, you may do so by enabling the `App\Http\Middleware\TrustHosts` middleware for your application. This is particularly important when your application offers password reset functionality.
42 |
43 | To learn more about this middleware, please consult the [`TrustHosts` middleware documentation](/docs/{{version}}/requests#configuring-trusted-hosts).
44 |
45 |
46 | ## Routing
47 |
48 | To properly implement support for allowing users to reset their passwords, we will need to define several routes. First, we will need a pair of routes to handle allowing the user to request a password reset link via their email address. Second, we will need a pair of routes to handle actually resetting the password once the user visits the password reset link that is emailed to them and completes the password reset form.
49 |
50 |
51 | ### Requesting The Password Reset Link
52 |
53 |
54 | #### The Password Reset Link Request Form
55 |
56 | First, we will define the routes that are needed to request password reset links. To get started, we will define a route that returns a view with the password reset link request form:
57 |
58 | Route::get('/forgot-password', function () {
59 | return view('auth.forgot-password');
60 | })->middleware('guest')->name('password.request');
61 |
62 | The view that is returned by this route should have a form containing an `email` field, which will allow the user to request a password reset link for a given email address.
63 |
64 |
65 | #### Handling The Form Submission
66 |
67 | Next, we will define a route that handles the form submission request from the "forgot password" view. This route will be responsible for validating the email address and sending the password reset request to the corresponding user:
68 |
69 | use Illuminate\Http\Request;
70 | use Illuminate\Support\Facades\Password;
71 |
72 | Route::post('/forgot-password', function (Request $request) {
73 | $request->validate(['email' => 'required|email']);
74 |
75 | $status = Password::sendResetLink(
76 | $request->only('email')
77 | );
78 |
79 | return $status === Password::RESET_LINK_SENT
80 | ? back()->with(['status' => __($status)])
81 | : back()->withErrors(['email' => __($status)]);
82 | })->middleware('guest')->name('password.email');
83 |
84 | Before moving on, let's examine this route in more detail. First, the request's `email` attribute is validated. Next, we will use Laravel's built-in "password broker" (via the `Password` facade) to send a password reset link to the user. The password broker will take care of retrieving the user by the given field (in this case, the email address) and sending the user a password reset link via Laravel's built-in [notification system](/docs/{{version}}/notifications).
85 |
86 | The `sendResetLink` method returns a "status" slug. This status may be translated using Laravel's [localization](/docs/{{version}}/localization) helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's `lang/{lang}/passwords.php` language file. An entry for each possible value of the status slug is located within the `passwords` language file.
87 |
88 | You may be wondering how Laravel knows how to retrieve the user record from your application's database when calling the `Password` facade's `sendResetLink` method. The Laravel password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the `passwords` configuration array of your `config/auth.php` configuration file. To learn more about writing custom user providers, consult the [authentication documentation](/docs/{{version}}/authentication#adding-custom-user-providers).
89 |
90 | > {tip} When manually implementing password resets, you are required to define the contents of the views and routes yourself. If you would like scaffolding that includes all necessary authentication and verification logic, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits).
91 |
92 |
93 | ### Resetting The Password
94 |
95 |
96 | #### The Password Reset Form
97 |
98 | Next, we will define the routes necessary to actually reset the password once the user clicks on the password reset link that has been emailed to them and provides a new password. First, let's define the route that will display the reset password form that is displayed when the user clicks the reset password link. This route will receive a `token` parameter that we will use later to verify the password reset request:
99 |
100 | Route::get('/reset-password/{token}', function ($token) {
101 | return view('auth.reset-password', ['token' => $token]);
102 | })->middleware('guest')->name('password.reset');
103 |
104 | The view that is returned by this route should display a form containing an `email` field, a `password` field, a `password_confirmation` field, and a hidden `token` field, which should contain the value of the secret `$token` received by our route.
105 |
106 |
107 | #### Handling The Form Submission
108 |
109 | Of course, we need to define a route to actually handle the password reset form submission. This route will be responsible for validating the incoming request and updating the user's password in the database:
110 |
111 | use Illuminate\Auth\Events\PasswordReset;
112 | use Illuminate\Http\Request;
113 | use Illuminate\Support\Facades\Hash;
114 | use Illuminate\Support\Facades\Password;
115 | use Illuminate\Support\Str;
116 |
117 | Route::post('/reset-password', function (Request $request) {
118 | $request->validate([
119 | 'token' => 'required',
120 | 'email' => 'required|email',
121 | 'password' => 'required|min:8|confirmed',
122 | ]);
123 |
124 | $status = Password::reset(
125 | $request->only('email', 'password', 'password_confirmation', 'token'),
126 | function ($user, $password) {
127 | $user->forceFill([
128 | 'password' => Hash::make($password)
129 | ])->setRememberToken(Str::random(60));
130 |
131 | $user->save();
132 |
133 | event(new PasswordReset($user));
134 | }
135 | );
136 |
137 | return $status === Password::PASSWORD_RESET
138 | ? redirect()->route('login')->with('status', __($status))
139 | : back()->withErrors(['email' => [__($status)]]);
140 | })->middleware('guest')->name('password.update');
141 |
142 | Before moving on, let's examine this route in more detail. First, the request's `token`, `email`, and `password` attributes are validated. Next, we will use Laravel's built-in "password broker" (via the `Password` facade) to validate the password reset request credentials.
143 |
144 | If the token, email address, and password given to the password broker are valid, the closure passed to the `reset` method will be invoked. Within this closure, which receives the user instance and the plain-text password provided to the password reset form, we may update the user's password in the database.
145 |
146 | The `reset` method returns a "status" slug. This status may be translated using Laravel's [localization](/docs/{{version}}/localization) helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's `lang/{lang}/passwords.php` language file. An entry for each possible value of the status slug is located within the `passwords` language file.
147 |
148 | Before moving on, you may be wondering how Laravel knows how to retrieve the user record from your application's database when calling the `Password` facade's `reset` method. The Laravel password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the `passwords` configuration array of your `config/auth.php` configuration file. To learn more about writing custom user providers, consult the [authentication documentation](/docs/{{version}}/authentication#adding-custom-user-providers).
149 |
150 |
151 | ## Deleting Expired Tokens
152 |
153 | Password reset tokens that have expired will still be present within your database. However, you may easily delete these records using the `auth:clear-resets` Artisan command:
154 |
155 | ```shell
156 | php artisan auth:clear-resets
157 | ```
158 |
159 | If you would like to automate this process, consider adding the command to your application's [scheduler](/docs/{{version}}/scheduling):
160 |
161 | $schedule->command('auth:clear-resets')->everyFifteenMinutes();
162 |
163 |
164 | ## Customization
165 |
166 |
167 | #### Reset Link Customization
168 |
169 | You may customize the password reset link URL using the `createUrlUsing` method provided by the `ResetPassword` notification class. This method accepts a closure which receives the user instance that is receiving the notification as well as the password reset link token. Typically, you should call this method from your `App\Providers\AuthServiceProvider` service provider's `boot` method:
170 |
171 | use Illuminate\Auth\Notifications\ResetPassword;
172 |
173 | /**
174 | * Register any authentication / authorization services.
175 | *
176 | * @return void
177 | */
178 | public function boot()
179 | {
180 | $this->registerPolicies();
181 |
182 | ResetPassword::createUrlUsing(function ($user, string $token) {
183 | return 'https://example.com/reset-password?token='.$token;
184 | });
185 | }
186 |
187 |
188 | #### Reset Email Customization
189 |
190 | You may easily modify the notification class used to send the password reset link to the user. To get started, override the `sendPasswordResetNotification` method on your `App\Models\User` model. Within this method, you may send the notification using any [notification class](/docs/{{version}}/notifications) of your own creation. The password reset `$token` is the first argument received by the method. You may use this `$token` to build the password reset URL of your choice and send your notification to the user:
191 |
192 | use App\Notifications\ResetPasswordNotification;
193 |
194 | /**
195 | * Send a password reset notification to the user.
196 | *
197 | * @param string $token
198 | * @return void
199 | */
200 | public function sendPasswordResetNotification($token)
201 | {
202 | $url = 'https://example.com/reset-password?token='.$token;
203 |
204 | $this->notify(new ResetPasswordNotification($url));
205 | }
206 |
--------------------------------------------------------------------------------
/providers.md:
--------------------------------------------------------------------------------
1 | # Service Providers
2 |
3 | - [Introduction](#introduction)
4 | - [Writing Service Providers](#writing-service-providers)
5 | - [The Register Method](#the-register-method)
6 | - [The Boot Method](#the-boot-method)
7 | - [Registering Providers](#registering-providers)
8 | - [Deferred Providers](#deferred-providers)
9 |
10 |
11 | ## Introduction
12 |
13 | Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.
14 |
15 | But, what do we mean by "bootstrapped"? In general, we mean **registering** things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
16 |
17 | If you open the `config/app.php` file included with Laravel, you will see a `providers` array. These are all of the service provider classes that will be loaded for your application. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others. Many of these providers are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.
18 |
19 | In this overview, you will learn how to write your own service providers and register them with your Laravel application.
20 |
21 | > {tip} If you would like to learn more about how Laravel handles requests and works internally, check out our documentation on the Laravel [request lifecycle](/docs/{{version}}/lifecycle).
22 |
23 |
24 | ## Writing Service Providers
25 |
26 | All service providers extend the `Illuminate\Support\ServiceProvider` class. Most service providers contain a `register` and a `boot` method. Within the `register` method, you should **only bind things into the [service container](/docs/{{version}}/container)**. You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method.
27 |
28 | The Artisan CLI can generate a new provider via the `make:provider` command:
29 |
30 | ```shell
31 | php artisan make:provider RiakServiceProvider
32 | ```
33 |
34 |
35 | ### The Register Method
36 |
37 | As mentioned previously, within the `register` method, you should only bind things into the [service container](/docs/{{version}}/container). You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method. Otherwise, you may accidentally use a service that is provided by a service provider which has not loaded yet.
38 |
39 | Let's take a look at a basic service provider. Within any of your service provider methods, you always have access to the `$app` property which provides access to the service container:
40 |
41 | app->singleton(Connection::class, function ($app) {
58 | return new Connection(config('riak'));
59 | });
60 | }
61 | }
62 |
63 | This service provider only defines a `register` method, and uses that method to define an implementation of `App\Services\Riak\Connection` in the service container. If you're not yet familiar with Laravel's service container, check out [its documentation](/docs/{{version}}/container).
64 |
65 |
66 | #### The `bindings` And `singletons` Properties
67 |
68 | If your service provider registers many simple bindings, you may wish to use the `bindings` and `singletons` properties instead of manually registering each container binding. When the service provider is loaded by the framework, it will automatically check for these properties and register their bindings:
69 |
70 | DigitalOceanServerProvider::class,
90 | ];
91 |
92 | /**
93 | * All of the container singletons that should be registered.
94 | *
95 | * @var array
96 | */
97 | public $singletons = [
98 | DowntimeNotifier::class => PingdomDowntimeNotifier::class,
99 | ServerProvider::class => ServerToolsProvider::class,
100 | ];
101 | }
102 |
103 |
104 | ### The Boot Method
105 |
106 | So, what if we need to register a [view composer](/docs/{{version}}/views#view-composers) within our service provider? This should be done within the `boot` method. **This method is called after all other service providers have been registered**, meaning you have access to all other services that have been registered by the framework:
107 |
108 |
131 | #### Boot Method Dependency Injection
132 |
133 | You may type-hint dependencies for your service provider's `boot` method. The [service container](/docs/{{version}}/container) will automatically inject any dependencies you need:
134 |
135 | use Illuminate\Contracts\Routing\ResponseFactory;
136 |
137 | /**
138 | * Bootstrap any application services.
139 | *
140 | * @param \Illuminate\Contracts\Routing\ResponseFactory $response
141 | * @return void
142 | */
143 | public function boot(ResponseFactory $response)
144 | {
145 | $response->macro('serialized', function ($value) {
146 | //
147 | });
148 | }
149 |
150 |
151 | ## Registering Providers
152 |
153 | All service providers are registered in the `config/app.php` configuration file. This file contains a `providers` array where you can list the class names of your service providers. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others.
154 |
155 | To register your provider, add it to the array:
156 |
157 | 'providers' => [
158 | // Other Service Providers
159 |
160 | App\Providers\ComposerServiceProvider::class,
161 | ],
162 |
163 |
164 | ## Deferred Providers
165 |
166 | If your provider is **only** registering bindings in the [service container](/docs/{{version}}/container), you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application, since it is not loaded from the filesystem on every request.
167 |
168 | Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider.
169 |
170 | To defer the loading of a provider, implement the `\Illuminate\Contracts\Support\DeferrableProvider` interface and define a `provides` method. The `provides` method should return the service container bindings registered by the provider:
171 |
172 | app->singleton(Connection::class, function ($app) {
190 | return new Connection($app['config']['riak']);
191 | });
192 | }
193 |
194 | /**
195 | * Get the services provided by the provider.
196 | *
197 | * @return array
198 | */
199 | public function provides()
200 | {
201 | return [Connection::class];
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/rate-limiting.md:
--------------------------------------------------------------------------------
1 | # Rate Limiting
2 |
3 | - [Introduction](#introduction)
4 | - [Cache Configuration](#cache-configuration)
5 | - [Basic Usage](#basic-usage)
6 | - [Manually Incrementing Attempts](#manually-incrementing-attempts)
7 | - [Clearing Attempts](#clearing-attempts)
8 |
9 |
10 | ## Introduction
11 |
12 | Laravel includes a simple to use rate limiting abstraction which, in conjunction with your application's [cache](cache), provides an easy way to limit any action during a specified window of time.
13 |
14 | > {tip} If you are interested in rate limiting incoming HTTP requests, please consult the [rate limiter middleware documentation](routing#rate-limiting).
15 |
16 |
17 | ### Cache Configuration
18 |
19 | Typically, the rate limiter utilizes your default application cache as defined by the `default` key within your application's `cache` configuration file. However, you may specify which cache driver the rate limiter should use by defining a `limiter` key within your application's `cache` configuration file:
20 |
21 | 'default' => 'memcached',
22 |
23 | 'limiter' => 'redis',
24 |
25 |
26 | ## Basic Usage
27 |
28 | The `Illuminate\Support\Facades\RateLimiter` facade may be used to interact with the rate limiter. The simplest method offered by the rate limiter is the `attempt` method, which rate limits a given callback for a given number of seconds.
29 |
30 | The `attempt` method returns `false` when the callback has no remaining attempts available; otherwise, the `attempt` method will return the callback's result or `true`. The first argument accepted by the `attempt` method is a rate limiter "key", which may be any string of your choosing that represents the action being rate limited:
31 |
32 | use Illuminate\Support\Facades\RateLimiter;
33 |
34 | $executed = RateLimiter::attempt(
35 | 'send-message:'.$user->id,
36 | $perMinute = 5,
37 | function() {
38 | // Send message...
39 | }
40 | );
41 |
42 | if (! $executed) {
43 | return 'Too many messages sent!';
44 | }
45 |
46 |
47 | ### Manually Incrementing Attempts
48 |
49 | If you would like to manually interact with the rate limiter, a variety of other methods are available. For example, you may invoke the `tooManyAttempts` method to determine if a given rate limiter key has exceeded its maximum number of allowed attempts per minute:
50 |
51 | use Illuminate\Support\Facades\RateLimiter;
52 |
53 | if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $perMinute = 5)) {
54 | return 'Too many attempts!';
55 | }
56 |
57 | Alternatively, you may use the `remaining` method to retrieve the number of attempts remaining for a given key. If a given key has retries remaining, you may invoke the `hit` method to increment the number of total attempts:
58 |
59 | use Illuminate\Support\Facades\RateLimiter;
60 |
61 | if (RateLimiter::remaining('send-message:'.$user->id, $perMinute = 5)) {
62 | RateLimiter::hit('send-message:'.$user->id);
63 |
64 | // Send message...
65 | }
66 |
67 |
68 | #### Determining Limiter Availability
69 |
70 | When a key has no more attempts left, the `availableIn` method returns the number of seconds remaining until more attempts will be available:
71 |
72 | use Illuminate\Support\Facades\RateLimiter;
73 |
74 | if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $perMinute = 5)) {
75 | $seconds = RateLimiter::availableIn('send-message:'.$user->id);
76 |
77 | return 'You may try again in '.$seconds.' seconds.';
78 | }
79 |
80 |
81 | ### Clearing Attempts
82 |
83 | You may reset the number of attempts for a given rate limiter key using the `clear` method. For example, you may reset the number of attempts when a given message is read by the receiver:
84 |
85 | use App\Models\Message;
86 | use Illuminate\Support\Facades\RateLimiter;
87 |
88 | /**
89 | * Mark the message as read.
90 | *
91 | * @param \App\Models\Message $message
92 | * @return \App\Models\Message
93 | */
94 | public function read(Message $message)
95 | {
96 | $message->markAsRead();
97 |
98 | RateLimiter::clear('send-message:'.$message->user_id);
99 |
100 | return $message;
101 | }
102 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # التوثيق العربي لإطار عمل لارافيل
2 |
3 | ## دليل المشاركة في المشروع
4 | 1. المهمات موزعة على شكل issues في المستودع الخاص بالمشروع
5 | 2. قم بالرد على اي issue خاصة بملف تريد ترجمته بانك ستقوم بترجمته
6 | 3. قم بعمل بانشاء نسختك الخاصة (fork) من هذا المستودع
7 | 4. قم بترجمة النصوص الى اللغة العربية، ونحن نوصي الا تكون الترجمة حرفية بل يجب ان تشير الى معنى المصطلح او مهمته ثم اسم المصطلح باللغة الانجليزية بين قوسين، ويوجد امثلة في كل issue تشرح طريقة الترجمة المقترحة
8 | 5. عند الانتهاء من ترجمة الملف يمكنك عمل Pull request لكي يتاح للمطورين مراجعته ودمجه.
9 |
--------------------------------------------------------------------------------
/redirects.md:
--------------------------------------------------------------------------------
1 | # HTTP Redirects
2 |
3 | - [إنشاء عمليات إعادة التوجيه (Redirects)](#creating-redirects)
4 | - [ إعادة التوجيه لمسارات (routes) ذات أسماء](#redirecting-named-routes)
5 | - [ إعادة التوجيه لعمليات المتحكم (controller actions)](#redirecting-controller-actions)
6 | - [إعادة التوجيه مع بيانات مخزنة مؤقتاً في الجلسة (Flashed Session Data)](#redirecting-with-flashed-session-data)
7 |
8 |
9 | ## إنشاء عمليات إعادة التوجيه (Redirects)
10 |
11 | إن ردود إعادة التوجيه (redirect responses) هي نُسخ (instances) من الكائن `Illuminate\Http\RedirectResponse` تحتوي على الترويسات (headers) المطلوبة لإعادة توجيه المستخدم لرابط URL أخر. يوجد عدة طرق لإنشاء نسخة من الكائن `RedirectResponse` وأبسطها هو استعمال التابع المساعد `redirect`:
12 |
13 | ```php
14 | Route::get('/dashboard', function () {
15 | return redirect('/home/dashboard');
16 | });
17 | ```
18 |
19 | أحياناً قد ترغب بإعادة توجيه المستخدمين لموقعهم السابق، كما في حالة إرسالهم لبيانات استمارة (form) خاطئة. يمكنك ذلك باستخدام التابع المساعد `back`. وبما أن هذه الميزة تعتمد على [الجلسة (session)](/docs/{{version}}/session) تأكد بأن استدعاء التابع `back` يستعمل مجموعة البرمجيات الوسيطة (middleware group) التالية `web` أو أنه يخضع لتطبيق جميع البرمجيات الوسيطة (middleware) الخاصة بالجلسة:
20 |
21 | ```php
22 | Route::post('/user/profile', function () {
23 | // Validate the request...
24 |
25 | return back()->withInput();
26 | });
27 | ```
28 |
29 |
30 | ## إعادة التوجيه لمسارات (routes) ذات أسماء
31 |
32 | عندما تستخدم التابع المساعد `redirect` بدون تمرير وسطاء سيتم إعادة نسخة (instance) من نوع `Illuminate\Routing\Redirector`، مما يسمح لك باستدعاء أي طريقة على النسخة `Redirector`. على سبيل المثال لإنشاء رد `RedirectResponse` على مسار ذو اسم (named route) يمكنك استخدام الطريقة `route`:
33 |
34 | ```php
35 | return redirect()->route('login');
36 | ```
37 |
38 | وفي حال كون المسار (route) يحتوي على وسطاء يمكنك تمريرهم كوسيط ثانٍ للطريقة `route`:
39 |
40 | ```php
41 | // For a route with the following URI: profile/{id}
42 |
43 | return redirect()->route('profile', ['id' => 1]);
44 | ```
45 |
46 |
47 | #### تمرير النماذج (Eloquent Models) كوسطاء
48 |
49 | اذا كنت تعيد التوجيه لمسار (route) يحوي على وسيط "ID" خاص بنموذج (Eloquent Model)، يمكنك تمرير النموذج (model) نفسه. حيث أنه سيتم استخراج الخاصية "ID" تلقائياً:
50 |
51 |
52 | ```php
53 | // For a route with the following URI: profile/{id}
54 |
55 | return redirect()->route('profile', [$user]);
56 | ```
57 |
58 | اذا كنت تريد تغيير القيمة التي يتم استخراجها عند تمرير النموذج كوسيط للمسار (route) يجب عليك عمل override للطريقة `getRouteKey` في النموذج (Eloquent Model) الخاص بك.:
59 |
60 |
61 | ```php
62 | /**
63 | * Get the value of the model's route key.
64 | *
65 | * @return mixed
66 | */
67 | public function getRouteKey()
68 | {
69 | return $this->slug;
70 | }
71 | ```
72 |
73 |
74 | ## إعادة التوجيه لعمليات المتحكم (Controller actions)
75 |
76 | يمكنك أيضاً إنشاء إعادة توجيه (redirect) [لعمليات متحكم (controller actions)](/docs/{{version}}/controllers) عن طريق تمرير المتحكم واسم العملية للطريقة `action`:
77 |
78 |
79 | ```php
80 | use App\Http\Controllers\HomeController;
81 |
82 | return redirect()->action([HomeController::class, 'index']);
83 | ```
84 |
85 | في حال كان مسار المتحكم يحتاج لوسطاء يمكنك تمريرهم كوسيط ثانٍ للطريقة `action`:
86 |
87 | ```php
88 | return redirect()->action(
89 | [UserController::class, 'profile'], ['id' => 1]
90 | );
91 | ```
92 |
93 |
94 | ## إعادة التوجيه مع بيانات مخزنة مؤقتاً في الجلسة (Flashed Session Data)
95 |
96 | إن عملية إعادة التوجيه لرابط (URL) جديد مع [تخزين بيانات بشكل مؤقت في الجلسة (flashing data to the session)](/docs/{{version}}/session#flash-data) يتم عادة بنفس الوقت. ويتم ذلك بعد تنفيذ إجراء ما بنجاح فتقوم بتخزين رسالة نجاح في الجلسة (session). للسهولة يمكنك انشاء نسخة (instance) من الكائن `RedirectResponse` وتخزينها مؤقتاً في الجلسة في طريقة فردية سلسة ومتسلسلة:
97 |
98 | ```php
99 | Route::post('/user/profile', function () {
100 | // Update the user's profile...
101 |
102 | return redirect('/dashboard')->with('status', 'Profile updated!');
103 | });
104 | ```
105 |
106 | يمكنك استخدام الطريقة `withInput` التي تقدمها النسخة (instance) من الكائن `RedirectResponse` لتخزين بيانات الدخل الخاصة بالطلب (request) الحالي في الجلسة قبل إعادة توجيه المستخدم لمكان جديد. وعندما يتم تخزين البيانات في الجلسة يمكنك [استعادتها](/docs/{{version}}/requests#retrieving-old-input) بسهولة خلال الطلب (request) التالي:
107 |
108 | ```php
109 | return back()->withInput();
110 | ```
111 |
112 | بعد إعادة توجيه المستخدم يمكنك عرض الرسالة التي تم تخزينها مؤقتاً في [الجلسة](/docs/{{version}}/session). على سبيل المثال باستخدام [تركيب Blade](/docs/{{version}}/blade) التالي:
113 |
114 | ```blade
115 | @if (session('status'))
116 |
117 | {{ session('status') }}
118 |
119 | @endif
120 | ```
--------------------------------------------------------------------------------
/seeding.md:
--------------------------------------------------------------------------------
1 | # زراعة أو تعبئة قاعدة البيانات
2 |
3 | - [المقدمة](#introduction)
4 | - [كتابة الزارعين](#writing-seeders)
5 | - [استخدام مصانع النموذج](#using-model-factories)
6 | - [نداء زارعين اضافيين](#calling-additional-seeders)
7 | - [كتم أحداث الزارعين](#muting-model-events)
8 | - [تشغيل الزارعين](#running-seeders)
9 |
10 |
11 | ## المقدمة
12 |
13 | تتيح لارافل زراعة أو تعبئة قاعدة البيانات عن طريق صفوف الزرع، تتوضع صفوف التعبئة ضمن المجلد `database/seeders`
14 |
15 | افتراضيا تم تعريف الصف `DatabaseSeeder` لنستخدم الطريقة `call` لنداء بقية صفوف التعبئة،
16 | يسمح لك بالتحكم بأوامر التعبئة
17 |
18 |
19 | ## كتابة الزارعين
20 |
21 | لإنشاء زارع ننفذ الأمر `make:seeder` [Artisan command](/docs/{{version}}/artisan)
22 |
23 | يتوضع الزارعين المنشئين ضمن المجلد `database/seeders`
24 |
25 | ```shell
26 | php artisan make:seeder UserSeeder
27 | ```
28 |
29 |
30 | يحتوي صف الزارع افتراضيا على طريقة واحدة `run` تُنفذ هذه الطريقة عند نداء الأمر `db:seed` [Artisan command](/docs/{{version}}/artisan)
31 |
32 | يمكنك إدخال البيانات لقاعدة البيانات ضمن الطريقة `run`
33 |
34 | يمكن إدخال البيانات يدوياً باستخدام [query builder](/docs/{{version}}/queries أو [Eloquent model factories](/docs/{{version}}/database-testing#defining-model-factories)
35 |
36 |
37 | في المثال التالي إضافة تعليمة إدخال البيانات لقاعدة البيانات ضمن الطريقة `run`
38 |
39 | insert([
58 | 'name' => Str::random(10),
59 | 'email' => Str::random(10).'@gmail.com',
60 | 'password' => Hash::make('password'),
61 | ]);
62 | }
63 | }
64 |
65 |
66 |
67 | ### استخدام مصانع النموذج
68 | تخصيص يدويا واصفات لكل تعبئة نموذج عملية مرهقة
69 |
70 | بدلا من ذلك نستخدم [model factories](/docs/{{version}}/database-testing#defining-model-factories) لإنشاء كميات كبيرة من حقول قاعدة البيانات
71 |
72 | أولا راجع [model factory documentation](/docs/{{version}}/database-testing#defining-model-factories) لتتعلم كيف تُعرف المصانع
73 |
74 | في المثال ننشئ 50 مستخدم لكل مستخدم منشور واحد مرتبط به
75 |
76 | use App\Models\User;
77 |
78 | /**
79 | * Run the database seeders.
80 | *
81 | * @return void
82 | */
83 | public function run()
84 | {
85 | User::factory()
86 | ->count(50)
87 | ->hasPosts(1)
88 | ->create();
89 | }
90 |
91 |
92 | ### نداء زارعين إضافيين
93 |
94 |
95 | نستخدم الطريقة `call` ضمن الصف `DatabaseSeeder` لتنفيذ صفوف زرع إضافية
96 |
97 | يسمح استخدام الطريقة `call` بتقسيم تعبئة قواعد البيانات في عدة ملفات لذلك صف الزرع لا يصبح كبير جداً
98 |
99 | تقبل الطريقة `call` مصفوفة من صفوف الزارع التي يجب أن تُنفذ
100 |
101 | /**
102 | * Run the database seeders.
103 | *
104 | * @return void
105 | */
106 | public function run()
107 | {
108 | $this->call([
109 | UserSeeder::class,
110 | PostSeeder::class,
111 | CommentSeeder::class,
112 | ]);
113 | }
114 |
115 |
116 | ### كتم أحداث النموذج
117 |
118 | لمنع النماذج من إرسال الأحداث عند تشغيل التعبئة نستخدم الميزة `WithoutModelEvents`
119 |
120 |
121 | call([
140 | UserSeeder::class,
141 | ]);
142 | }
143 | }
144 |
145 |
146 | ## تشغيل الزارعين
147 |
148 |
149 | لتعبئة قواعد البيانات نستخدم الأمر `db:seed`
150 |
151 | يشغل الأمر `db:seed` الصف `Database\Seeders\DatabaseSeeder`
152 |
153 | يمكن استخدام الخيار `--class` لتخصيص صف زارع خاص ليعمل بشكل فردي
154 |
155 | ```shell
156 | php artisan db:seed
157 |
158 | php artisan db:seed --class=UserSeeder
159 | ```
160 |
161 | يمكن تعبئة قاعدة البيانات باستخدام الأمر `migrate:fresh` مع الخيار `--seed`
162 |
163 | سوف تحذف كل الجداول وتعيد تشغيل كل الترحيلات
164 |
165 | هذا الأمر نافع لإعادة بناء قاعدة البيانات بشكل كامل
166 |
167 | ```shell
168 | php artisan migrate:fresh --seed
169 | ```
170 |
171 |
172 | #### إجبار الزارعين للتشغيل في الإنتاج
173 |
174 | تسبب بعض عمليات التعبئة تعديل أو فقدان البيانات
175 |
176 | سوف تقوم بالتلقين للتأكيد قبل تنفيذ الزارعين في بيئة `production`
177 |
178 | لإجبار الزارعين للتشغيل بدون تلقين نستخدم العلم `--force`
179 |
180 | ```shell
181 | php artisan db:seed --force
182 | ```
183 |
--------------------------------------------------------------------------------
/socialite.md:
--------------------------------------------------------------------------------
1 | # Laravel Socialite
2 |
3 | - [مقدمة](#introduction)
4 | - [الاثبيا](#installation)
5 | - [تحديث Socialite](#upgrading-socialite)
6 | - [الإعداد](#configuration)
7 | - [المصادقة (Authentication)](#authentication)
8 | - [التوجيه (Routing)](#routing)
9 | - [المصادقة و التخزين](#authentication-and-storage)
10 | - [(Access Scopes) نطاقات الوصول](#access-scopes)
11 | - [بارامترات اختيارية](#optional-parameters)
12 | - [استرجاع تفاصيل المستخدم](#retrieving-user-details)
13 |
14 |
15 | ## المقدمة
16 |
17 | بالإضافة إلى المصادقة النموذجية القائمة على النموذج، يوفر Laravel أيضًا طريقة بسيطة, طريقة مريحة للمصادقة مع مزودي OAuth باستخدام [Laravel Socialite](https://github.com/laravel/socialite). تدعم Socialite حاليًا المصادقة مع Facebook و Twitter و LinkedIn و Google و GitHub و GitLab و Bitbucket.
18 |
19 | > {نصيحة} يوجد محولات خاصة بالمواقع الأخرى تستطيع إيجادها عبر الموقع [Socialite Providers](https://socialiteproviders.com/).
20 |
21 |
22 | ## التثبيت
23 |
24 | للبدء مع Socialite، استخدم مدير حزمة Composer لإضافة الحزمة إلى تبعيات مشروعك:
25 |
26 | ```shell
27 | composer require laravel/socialite
28 | ```
29 |
30 |
31 | ## تحديث Socialite
32 |
33 | عند الترقية إلى إصدار رئيسي جديد من Socialite، من المهم أن تراجع بعناية [دليل الترقية] (https://github.com/laravel/socialite/blob/master/UPGRADE.md).
34 |
35 |
36 | ## الإعداد
37 |
38 | قبل استخدام Socialite، ستحتاج إلى إضافة بيانات اعتماد لمزودي OAuth الذين يستخدمهم تطبيقك. يجب وضع أوراق الاعتماد هذه في ملف التكوين الخاص بتطبيقك "config/services.php"، ويجب استخدام المفتاح "facebook" أو "twitter" أو "linkedin" أو "google" أو "github" أو "gitlab" أو "bitbuket'، اعتمادًا على مقدمي الخدمة التي يتطلبها:
39 |
40 | 'github' => [
41 | 'client_id' => env('GITHUB_CLIENT_ID'),
42 | 'client_secret' => env('GITHUB_CLIENT_SECRET'),
43 | 'redirect' => 'http://example.com/callback-url',
44 | ],
45 |
46 | > {نصيحة} إذا كان خيار «إعادة التوجيه» يحتوي على مسار نسبي، فسيتم حله تلقائيًا إلى عنوان URL مؤهل تمامًا.
47 |
48 |
49 | ## المصادقة
50 |
51 |
52 | ### Routing إعادة التوجيه
53 |
54 | لمصادقة المستخدمين باستخدام مزود OAuth، ستحتاج إلى مسارين: أحدهما لإعادة توجيه المستخدم إلى مزود OAuth، والآخر لتلقي إعادة الاتصال من المزود بعد المصادقة. وتبين وحدة التحكم في المثال أدناه تنفيذ كلا المسارين:
55 |
56 | use Laravel\Socialite\Facades\Socialite;
57 |
58 | Route::get('/auth/redirect', function () {
59 | return Socialite::driver('github')->redirect();
60 | });
61 |
62 | Route::get('/auth/callback', function () {
63 | $user = Socialite::driver('github')->user();
64 |
65 | // $user->token
66 | });
67 |
68 | طريقة «إعادة التوجيه» التي توفرها واجهة «Socialite» تعتني بإعادة توجيه المستخدم إلى مزود OAuth، بينما ستقرأ طريقة «المستخدم» الطلب الوارد وتستعيد معلومات المستخدم من المزود بعد المصادقة عليها.
69 |
70 |
71 | ### المصادقة و التخزين
72 |
73 | بمجرد استرداد المستخدم من مزود OAuth، يمكنك تحديد ما إذا كان المستخدم موجودًا في قاعدة بيانات تطبيقك و [مصادقة المستخدم](/docs/{{version}}/authentication#authenticate-a-user-instance). إذا لم يكن المستخدم موجودًا في قاعدة بيانات تطبيقك، فستقوم عادةً بإنشاء سجل جديد في قاعدة بياناتك لتمثيل المستخدم:
74 |
75 | use App\Models\User;
76 | use Illuminate\Support\Facades\Auth;
77 | use Laravel\Socialite\Facades\Socialite;
78 |
79 | Route::get('/auth/callback', function () {
80 | $githubUser = Socialite::driver('github')->user();
81 |
82 | $user = User::where('github_id', $githubUser->id)->first();
83 |
84 | if ($user) {
85 | $user->update([
86 | 'github_token' => $githubUser->token,
87 | 'github_refresh_token' => $githubUser->refreshToken,
88 | ]);
89 | } else {
90 | $user = User::create([
91 | 'name' => $githubUser->name,
92 | 'email' => $githubUser->email,
93 | 'github_id' => $githubUser->id,
94 | 'github_token' => $githubUser->token,
95 | 'github_refresh_token' => $githubUser->refreshToken,
96 | ]);
97 | }
98 |
99 | Auth::login($user);
100 |
101 | return redirect('/dashboard');
102 | });
103 |
104 | > {نصيحة} لمزيد من المعلومات حول معلومات المستخدم المتاحة من مزودي OAuth المحددين، يرجى الرجوع إلى الوثائق على [استرجاع تفاصيل المستخدم](#retrieving-user-details).
105 |
106 |
107 | ### نطاقات الوصول
108 |
109 | قبل إعادة توجيه المستخدم، يمكنك أيضًا إضافة «نطاقات» إضافية إلى طلب المصادقة باستخدام طريقة «النطاقات». ستدمج هذه الطريقة جميع النطاقات الموجودة مع النطاقات التي توفرها:
110 |
111 | use Laravel\Socialite\Facades\Socialite;
112 |
113 | return Socialite::driver('github')
114 | ->scopes(['read:user', 'public_repo'])
115 | ->redirect();
116 |
117 | يمكنك كتابة جميع النطاقات الموجودة على طلب المصادقة باستخدام طريقة «set Scopes»:
118 |
119 | return Socialite::driver('github')
120 | ->setScopes(['read:user', 'public_repo'])
121 | ->redirect();
122 |
123 |
124 | ### بارامترات اختيارية
125 |
126 | يدعم عدد من مزودي OAuth المعلمات الاختيارية في طلب إعادة التوجيه. لإدراج أي معلمات اختيارية في الطلب، اتصل بطريقة «مع» مع مصفوفة ارتباطية:
127 |
128 | use Laravel\Socialite\Facades\Socialite;
129 |
130 | return Socialite::driver('google')
131 | ->with(['hd' => 'example.com'])
132 | ->redirect();
133 |
134 | > {ملاحظة} عند استخدام طريقة «مع»، احرص على عدم اجتياز أي كلمات رئيسية محفوظة مثل «الحالة» أو «الاستجابة _ الكتابة».
135 |
136 |
137 | ## استرجاع تفاصيل المستخدم
138 |
139 | بعد إعادة توجيه المستخدم مرة أخرى إلى مسار إعادة الاتصال بالمصادقة، يمكنك استرداد تفاصيل المستخدم باستخدام طريقة «مستخدم» Socialite. يوفر كائن المستخدم الذي أعادته طريقة «المستخدم» مجموعة متنوعة من الخصائص والطرق التي يمكنك استخدامها لتخزين المعلومات حول المستخدم في قاعدة بياناتك الخاصة. قد تكون الخصائص والطرق المختلفة متاحة اعتمادًا على ما إذا كان مزود OAuth الذي تقوم بالمصادقة عليه يدعم OAuth 1.0 أو OAuth 2.0:
140 |
141 | use Laravel\Socialite\Facades\Socialite;
142 |
143 | Route::get('/auth/callback', function () {
144 | $user = Socialite::driver('github')->user();
145 |
146 | // OAuth 2.0 providers...
147 | $token = $user->token;
148 | $refreshToken = $user->refreshToken;
149 | $expiresIn = $user->expiresIn;
150 |
151 | // OAuth 1.0 providers...
152 | $token = $user->token;
153 | $tokenSecret = $user->tokenSecret;
154 |
155 | // All providers...
156 | $user->getId();
157 | $user->getNickname();
158 | $user->getName();
159 | $user->getEmail();
160 | $user->getAvatar();
161 | });
162 |
163 |
164 | #### استرجاع تفاصيل المستخدم من الـ Token (OAuth2)
165 |
166 | إذا كان لديك بالفعل رمز وصول صالح للمستخدم، فيمكنك استرداد تفاصيله باستخدام طريقة Socialite's «UserFromToken»:
167 |
168 | use Laravel\Socialite\Facades\Socialite;
169 |
170 | $user = Socialite::driver('github')->userFromToken($token);
171 |
172 |
173 | #### استرداد تفاصيل المستخدم من الـ Token الـ Secret (OAuth1)
174 |
175 | إذا كان لديك بالفعل رمز وسر صالح للمستخدم، فيمكنك استرداد تفاصيله باستخدام طريقة Socialite "المستخدم من TokenAndSecret':
176 |
177 | use Laravel\Socialite\Facades\Socialite;
178 |
179 | $user = Socialite::driver('twitter')->userFromTokenAndSecret($token, $secret);
180 |
181 |
182 | #### Stateless مصادقة
183 |
184 | يمكن استخدام طريقة «stateless» لتعطيل التحقق من الجلسة بناءً على state محددة. هذا مفيد عند إضافة المصادقة عبر المنصات الإجتماعية إلى API:
185 |
186 | use Laravel\Socialite\Facades\Socialite;
187 |
188 | return Socialite::driver('google')->stateless()->user();
189 |
190 | > {ملاحظة} المصادقة عديمة الجنسية غير متاحة لـ Driver Twitter، الذي يستخدم OAuth 1.0 للمصادقة.
191 |
--------------------------------------------------------------------------------
/starter-kits.md:
--------------------------------------------------------------------------------
1 | # Starter Kits
2 |
3 | - [Introduction](#introduction)
4 | - [Laravel Breeze](#laravel-breeze)
5 | - [Installation](#laravel-breeze-installation)
6 | - [Breeze & Inertia](#breeze-and-inertia)
7 | - [Breeze & Next.js / API](#breeze-and-next)
8 | - [Laravel Jetstream](#laravel-jetstream)
9 |
10 |
11 | ## Introduction
12 |
13 | To give you a head start building your new Laravel application, we are happy to offer authentication and application starter kits. These kits automatically scaffold your application with the routes, controllers, and views you need to register and authenticate your application's users.
14 |
15 | While you are welcome to use these starter kits, they are not required. You are free to build your own application from the ground up by simply installing a fresh copy of Laravel. Either way, we know you will build something great!
16 |
17 |
18 | ## Laravel Breeze
19 |
20 | [Laravel Breeze](https://github.com/laravel/breeze) is a minimal, simple implementation of all of Laravel's [authentication features](/docs/{{version}}/authentication), including login, registration, password reset, email verification, and password confirmation. Laravel Breeze's default view layer is made up of simple [Blade templates](/docs/{{version}}/blade) styled with [Tailwind CSS](https://tailwindcss.com).
21 |
22 | Breeze provides a wonderful starting point for beginning a fresh Laravel application and is also great choice for projects that plan to take their Blade templates to the next level with [Laravel Livewire](https://laravel-livewire.com).
23 |
24 |
25 | ### Installation
26 |
27 | First, you should [create a new Laravel application](/docs/{{version}}/installation), configure your database, and run your [database migrations](/docs/{{version}}/migrations):
28 |
29 | ```shell
30 | curl -s https://laravel.build/example-app | bash
31 |
32 | cd example-app
33 |
34 | php artisan migrate
35 | ```
36 |
37 | Once you have created a new Laravel application, you may install Laravel Breeze using Composer:
38 |
39 | ```shell
40 | composer require laravel/breeze --dev
41 | ```
42 |
43 | After Composer has installed the Laravel Breeze package, you may run the `breeze:install` Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application. Laravel Breeze publishes all of its code to your application so that you have full control and visibility over its features and implementation. After Breeze is installed, you should also compile your assets so that your application's CSS file is available:
44 |
45 | ```shell
46 | php artisan breeze:install
47 |
48 | npm install
49 | npm run dev
50 | php artisan migrate
51 | ```
52 |
53 | Next, you may navigate to your application's `/login` or `/register` URLs in your web browser. All of Breeze's routes are defined within the `routes/auth.php` file.
54 |
55 | > {tip} To learn more about compiling your application's CSS and JavaScript, check out the [Laravel Mix documentation](/docs/{{version}}/mix#running-mix).
56 |
57 |
58 | ### Breeze & Inertia
59 |
60 | Laravel Breeze also offers an [Inertia.js](https://inertiajs.com) frontend implementation powered by Vue or React. To use an Inertia stack, specify `vue` or `react` as your desired stack when executing the `breeze:install` Artisan command:
61 |
62 | ```shell
63 | php artisan breeze:install vue
64 |
65 | // Or...
66 |
67 | php artisan breeze:install react
68 |
69 | npm install
70 | npm run dev
71 | php artisan migrate
72 | ```
73 |
74 |
75 | ### Breeze & Next.js / API
76 |
77 | Laravel Breeze can also scaffold an authentication API that is ready to authenticate modern JavaScript applications such as those powered by [Next](https://nextjs.org), [Nuxt](https://nuxtjs.org), and others. To get started, specify the `api` stack as your desired stack when executing the `breeze:install` Artisan command:
78 |
79 | ```shell
80 | php artisan breeze:install api
81 |
82 | php artisan migrate
83 | ```
84 |
85 | During installation, Breeze will add a `FRONTEND_URL` environment variable to your application's `.env` file. This URL should be the URL of your JavaScript application. This will typically be `http://localhost:3000` during local development. In addition, you should ensure that your `APP_URL` is set to `http://localhost:8000`, which is the default URL used by the `serve` Artisan command.
86 |
87 |
88 | #### Next.js Reference Implementation
89 |
90 | Finally, you are ready to pair this backend with the frontend of your choice. A Next reference implementation of the Breeze frontend is [available on GitHub](https://github.com/laravel/breeze-next). This frontend is maintained by Laravel and contains the same user interface as the traditional Blade and Inertia stacks provided by Breeze.
91 |
92 |
93 | ## Laravel Jetstream
94 |
95 | While Laravel Breeze provides a simple and minimal starting point for building a Laravel application, Jetstream augments that functionality with more robust features and additional frontend technology stacks. **For those brand new to Laravel, we recommend learning the ropes with Laravel Breeze before graduating to Laravel Jetstream.**
96 |
97 | Jetstream provides a beautifully designed application scaffolding for Laravel and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management. Jetstream is designed using [Tailwind CSS](https://tailwindcss.com) and offers your choice of [Livewire](https://laravel-livewire.com) or [Inertia.js](https://inertiajs.com) driven frontend scaffolding.
98 |
99 | Complete documentation for installing Laravel Jetstream can be found within the [official Jetstream documentation](https://jetstream.laravel.com/2.x/introduction.html).
100 |
--------------------------------------------------------------------------------
/testing.md:
--------------------------------------------------------------------------------
1 | # Testing: Getting Started
2 |
3 | - [Introduction](#introduction)
4 | - [Environment](#environment)
5 | - [Creating Tests](#creating-tests)
6 | - [Running Tests](#running-tests)
7 | - [Running Tests In Parallel](#running-tests-in-parallel)
8 | - [Reporting Test Coverage](#reporting-test-coverage)
9 |
10 |
11 | ## Introduction
12 |
13 | Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box and a `phpunit.xml` file is already set up for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications.
14 |
15 | By default, your application's `tests` directory contains two directories: `Feature` and `Unit`. Unit tests are tests that focus on a very small, isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your "Unit" test directory do not boot your Laravel application and therefore are unable to access your application's database or other framework services.
16 |
17 | Feature tests may test a larger portion of your code, including how several objects interact with each other or even a full HTTP request to a JSON endpoint. **Generally, most of your tests should be feature tests. These types of tests provide the most confidence that your system as a whole is functioning as intended.**
18 |
19 | An `ExampleTest.php` file is provided in both the `Feature` and `Unit` test directories. After installing a new Laravel application, execute the `vendor/bin/phpunit` or `php artisan test` commands to run your tests.
20 |
21 |
22 | ## Environment
23 |
24 | When running tests, Laravel will automatically set the [configuration environment](/docs/{{version}}/configuration#environment-configuration) to `testing` because of the environment variables defined in the `phpunit.xml` file. Laravel also automatically configures the session and cache to the `array` driver while testing, meaning no session or cache data will be persisted while testing.
25 |
26 | You are free to define other testing environment configuration values as necessary. The `testing` environment variables may be configured in your application's `phpunit.xml` file, but make sure to clear your configuration cache using the `config:clear` Artisan command before running your tests!
27 |
28 |
29 | #### The `.env.testing` Environment File
30 |
31 | In addition, you may create a `.env.testing` file in the root of your project. This file will be used instead of the `.env` file when running PHPUnit tests or executing Artisan commands with the `--env=testing` option.
32 |
33 |
34 | #### The `CreatesApplication` Trait
35 |
36 | Laravel includes a `CreatesApplication` trait that is applied to your application's base `TestCase` class. This trait contains a `createApplication` method that bootstraps the Laravel application before running your tests. It's important that you leave this trait at its original location as some features, such as Laravel's parallel testing feature, depend on it.
37 |
38 |
39 | ## Creating Tests
40 |
41 | To create a new test case, use the `make:test` Artisan command. By default, tests will be placed in the `tests/Feature` directory:
42 |
43 | ```shell
44 | php artisan make:test UserTest
45 | ```
46 |
47 | If you would like to create a test within the `tests/Unit` directory, you may use the `--unit` option when executing the `make:test` command:
48 |
49 | ```shell
50 | php artisan make:test UserTest --unit
51 | ```
52 |
53 | If you would like to create a [Pest PHP](https://pestphp.com) test, you may provide the `--pest` option to the `make:test` command:
54 |
55 | ```shell
56 | php artisan make:test UserTest --pest
57 | php artisan make:test UserTest --unit --pest
58 | ```
59 |
60 | > {tip} Test stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization).
61 |
62 | Once the test has been generated, you may define test methods as you normally would using [PHPUnit](https://phpunit.de). To run your tests, execute the `vendor/bin/phpunit` or `php artisan test` command from your terminal:
63 |
64 | assertTrue(true);
80 | }
81 | }
82 |
83 | > {note} If you define your own `setUp` / `tearDown` methods within a test class, be sure to call the respective `parent::setUp()` / `parent::tearDown()` methods on the parent class.
84 |
85 |
86 | ## Running Tests
87 |
88 | As mentioned previously, once you've written tests, you may run them using `phpunit`:
89 |
90 | ```shell
91 | ./vendor/bin/phpunit
92 | ```
93 |
94 | In addition to the `phpunit` command, you may use the `test` Artisan command to run your tests. The Artisan test runner provides verbose test reports in order to ease development and debugging:
95 |
96 | ```shell
97 | php artisan test
98 | ```
99 |
100 | Any arguments that can be passed to the `phpunit` command may also be passed to the Artisan `test` command:
101 |
102 | ```shell
103 | php artisan test --testsuite=Feature --stop-on-failure
104 | ```
105 |
106 |
107 | ### Running Tests In Parallel
108 |
109 | By default, Laravel and PHPUnit execute your tests sequentially within a single process. However, you may greatly reduce the amount of time it takes to run your tests by running tests simultaneously across multiple processes. To get started, ensure your application depends on version `^5.3` or greater of the `nunomaduro/collision` package. Then, include the `--parallel` option when executing the `test` Artisan command:
110 |
111 | ```shell
112 | php artisan test --parallel
113 | ```
114 |
115 | By default, Laravel will create as many processes as there are available CPU cores on your machine. However, you may adjust the number of processes using the `--processes` option:
116 |
117 | ```shell
118 | php artisan test --parallel --processes=4
119 | ```
120 |
121 | > {note} When running tests in parallel, some PHPUnit options (such as `--do-not-cache-result`) may not be available.
122 |
123 |
124 | #### Parallel Testing & Databases
125 |
126 | Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create and use `your_db_test_1` and `your_db_test_2` test databases.
127 |
128 | By default, test databases persist between calls to the `test` Artisan command so that they can be used again by subsequent `test` invocations. However, you may re-create them using the `--recreate-databases` option:
129 |
130 | ```shell
131 | php artisan test --parallel --recreate-databases
132 | ```
133 |
134 |
135 | #### Parallel Testing Hooks
136 |
137 | Occasionally, you may need to prepare certain resources used by your application's tests so they may be safely used by multiple test processes.
138 |
139 | Using the `ParallelTesting` facade, you may specify code to be executed on the `setUp` and `tearDown` of a process or test case. The given closures receive the `$token` and `$testCase` variables that contain the process token and the current test case, respectively:
140 |
141 |
182 | #### Accessing The Parallel Testing Token
183 |
184 | If you would like to access to current parallel process "token" from any other location in your application's test code, you may use the `token` method. This token is a unique, string identifier for an individual test process and may be used to segment resources across parallel test processes. For example, Laravel automatically appends this token to the end of the test databases created by each parallel testing process:
185 |
186 | $token = ParallelTesting::token();
187 |
188 |
189 | ### Reporting Test Coverage
190 |
191 | > {note} This feature requires [Xdebug](https://xdebug.org) or [PCOV](https://pecl.php.net/package/pcov).
192 |
193 | When running your application tests, you may want to determine whether your test cases are actually covering the application code and how much application code is used when running your tests. To accomplish this, you may provide the `--coverage` option when invoking the `test` command:
194 |
195 | ```shell
196 | php artisan test --coverage
197 | ```
198 |
199 |
200 | #### Enforcing A Minimum Coverage Threshold
201 |
202 | You may use the `--min` option to define a minimum test coverage threshold for your application. The test suite will fail if this threshold is not met:
203 |
204 | ```shell
205 | php artisan test --coverage --min=80.3
206 | ```
207 |
--------------------------------------------------------------------------------
/urls.md:
--------------------------------------------------------------------------------
1 | # URL Generation
2 |
3 | - [Introduction](#introduction)
4 | - [The Basics](#the-basics)
5 | - [Generating URLs](#generating-urls)
6 | - [Accessing The Current URL](#accessing-the-current-url)
7 | - [URLs For Named Routes](#urls-for-named-routes)
8 | - [Signed URLs](#signed-urls)
9 | - [URLs For Controller Actions](#urls-for-controller-actions)
10 | - [Default Values](#default-values)
11 |
12 |
13 | ## Introduction
14 |
15 | Laravel provides several helpers to assist you in generating URLs for your application. These helpers are primarily helpful when building links in your templates and API responses, or when generating redirect responses to another part of your application.
16 |
17 |
18 | ## The Basics
19 |
20 |
21 | ### Generating URLs
22 |
23 | The `url` helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request being handled by the application:
24 |
25 | $post = App\Models\Post::find(1);
26 |
27 | echo url("/posts/{$post->id}");
28 |
29 | // http://example.com/posts/1
30 |
31 |
32 | ### Accessing The Current URL
33 |
34 | If no path is provided to the `url` helper, an `Illuminate\Routing\UrlGenerator` instance is returned, allowing you to access information about the current URL:
35 |
36 | // Get the current URL without the query string...
37 | echo url()->current();
38 |
39 | // Get the current URL including the query string...
40 | echo url()->full();
41 |
42 | // Get the full URL for the previous request...
43 | echo url()->previous();
44 |
45 | Each of these methods may also be accessed via the `URL` [facade](/docs/{{version}}/facades):
46 |
47 | use Illuminate\Support\Facades\URL;
48 |
49 | echo URL::current();
50 |
51 |
52 | ## URLs For Named Routes
53 |
54 | The `route` helper may be used to generate URLs to [named routes](/docs/{{version}}/routing#named-routes). Named routes allow you to generate URLs without being coupled to the actual URL defined on the route. Therefore, if the route's URL changes, no changes need to be made to your calls to the `route` function. For example, imagine your application contains a route defined like the following:
55 |
56 | Route::get('/post/{post}', function (Post $post) {
57 | //
58 | })->name('post.show');
59 |
60 | To generate a URL to this route, you may use the `route` helper like so:
61 |
62 | echo route('post.show', ['post' => 1]);
63 |
64 | // http://example.com/post/1
65 |
66 | Of course, the `route` helper may also be used to generate URLs for routes with multiple parameters:
67 |
68 | Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) {
69 | //
70 | })->name('comment.show');
71 |
72 | echo route('comment.show', ['post' => 1, 'comment' => 3]);
73 |
74 | // http://example.com/post/1/comment/3
75 |
76 | Any additional array elements that do not correspond to the route's definition parameters will be added to the URL's query string:
77 |
78 | echo route('post.show', ['post' => 1, 'search' => 'rocket']);
79 |
80 | // http://example.com/post/1?search=rocket
81 |
82 |
83 | #### Eloquent Models
84 |
85 | You will often be generating URLs using the route key (typically the primary key) of [Eloquent models](/docs/{{version}}/eloquent). For this reason, you may pass Eloquent models as parameter values. The `route` helper will automatically extract the model's route key:
86 |
87 | echo route('post.show', ['post' => $post]);
88 |
89 |
90 | ### Signed URLs
91 |
92 | Laravel allows you to easily create "signed" URLs to named routes. These URLs have a "signature" hash appended to the query string which allows Laravel to verify that the URL has not been modified since it was created. Signed URLs are especially useful for routes that are publicly accessible yet need a layer of protection against URL manipulation.
93 |
94 | For example, you might use signed URLs to implement a public "unsubscribe" link that is emailed to your customers. To create a signed URL to a named route, use the `signedRoute` method of the `URL` facade:
95 |
96 | use Illuminate\Support\Facades\URL;
97 |
98 | return URL::signedRoute('unsubscribe', ['user' => 1]);
99 |
100 | If you would like to generate a temporary signed route URL that expires after a specified amount of time, you may use the `temporarySignedRoute` method. When Laravel validates a temporary signed route URL, it will ensure that the expiration timestamp that is encoded into the signed URL has not elapsed:
101 |
102 | use Illuminate\Support\Facades\URL;
103 |
104 | return URL::temporarySignedRoute(
105 | 'unsubscribe', now()->addMinutes(30), ['user' => 1]
106 | );
107 |
108 |
109 | #### Validating Signed Route Requests
110 |
111 | To verify that an incoming request has a valid signature, you should call the `hasValidSignature` method on the incoming `Illuminate\Http\Request` instance:
112 |
113 | use Illuminate\Http\Request;
114 |
115 | Route::get('/unsubscribe/{user}', function (Request $request) {
116 | if (! $request->hasValidSignature()) {
117 | abort(401);
118 | }
119 |
120 | // ...
121 | })->name('unsubscribe');
122 |
123 | Sometimes, you may need to allow your application's frontend to append data to a signed URL, such as when performing client-side pagination. Therefore, you can specify request query parameters that should be ignored when validating a signed URL using the `hasValidSignatureWhileIgnoring` method. Remember, ignoring parameters allows anyone to modify those parameters on the request:
124 |
125 | if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) {
126 | abort(401);
127 | }
128 |
129 | Instead of validating signed URLs using the incoming request instance, you may assign the `Illuminate\Routing\Middleware\ValidateSignature` [middleware](/docs/{{version}}/middleware) to the route. If it is not already present, you should assign this middleware a key in your HTTP kernel's `routeMiddleware` array:
130 |
131 | /**
132 | * The application's route middleware.
133 | *
134 | * These middleware may be assigned to groups or used individually.
135 | *
136 | * @var array
137 | */
138 | protected $routeMiddleware = [
139 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
140 | ];
141 |
142 | Once you have registered the middleware in your kernel, you may attach it to a route. If the incoming request does not have a valid signature, the middleware will automatically return a `403` HTTP response:
143 |
144 | Route::post('/unsubscribe/{user}', function (Request $request) {
145 | // ...
146 | })->name('unsubscribe')->middleware('signed');
147 |
148 |
149 | #### Responding To Invalid Signed Routes
150 |
151 | When someone visits a signed URL that has expired, they will receive a generic error page for the `403` HTTP status code. However, you can customize this behavior by defining a custom "renderable" closure for the `InvalidSignatureException` exception in your exception handler. This closure should return an HTTP response:
152 |
153 | use Illuminate\Routing\Exceptions\InvalidSignatureException;
154 |
155 | /**
156 | * Register the exception handling callbacks for the application.
157 | *
158 | * @return void
159 | */
160 | public function register()
161 | {
162 | $this->renderable(function (InvalidSignatureException $e) {
163 | return response()->view('error.link-expired', [], 403);
164 | });
165 | }
166 |
167 |
168 | ## URLs For Controller Actions
169 |
170 | The `action` function generates a URL for the given controller action:
171 |
172 | use App\Http\Controllers\HomeController;
173 |
174 | $url = action([HomeController::class, 'index']);
175 |
176 | If the controller method accepts route parameters, you may pass an associative array of route parameters as the second argument to the function:
177 |
178 | $url = action([UserController::class, 'profile'], ['id' => 1]);
179 |
180 |
181 | ## Default Values
182 |
183 | For some applications, you may wish to specify request-wide default values for certain URL parameters. For example, imagine many of your routes define a `{locale}` parameter:
184 |
185 | Route::get('/{locale}/posts', function () {
186 | //
187 | })->name('post.index');
188 |
189 | It is cumbersome to always pass the `locale` every time you call the `route` helper. So, you may use the `URL::defaults` method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a [route middleware](/docs/{{version}}/middleware#assigning-middleware-to-routes) so that you have access to the current request:
190 |
191 | $request->user()->locale]);
210 |
211 | return $next($request);
212 | }
213 | }
214 |
215 | Once the default value for the `locale` parameter has been set, you are no longer required to pass its value when generating URLs via the `route` helper.
216 |
217 |
218 | #### URL Defaults & Middleware Priority
219 |
220 | Setting URL default values can interfere with Laravel's handling of implicit model bindings. Therefore, you should [prioritize your middleware](/docs/{{version}}/middleware#sorting-middleware) that set URL defaults to be executed before Laravel's own `SubstituteBindings` middleware. You can accomplish this by making sure your middleware occurs before the `SubstituteBindings` middleware within the `$middlewarePriority` property of your application's HTTP kernel.
221 |
222 | The `$middlewarePriority` property is defined in the base `Illuminate\Foundation\Http\Kernel` class. You may copy its definition from that class and overwrite it in your application's HTTP kernel in order to modify it:
223 |
224 | /**
225 | * The priority-sorted list of middleware.
226 | *
227 | * This forces non-global middleware to always be in the given order.
228 | *
229 | * @var array
230 | */
231 | protected $middlewarePriority = [
232 | // ...
233 | \App\Http\Middleware\SetDefaultLocaleForUrls::class,
234 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
235 | // ...
236 | ];
237 |
--------------------------------------------------------------------------------
/verification.md:
--------------------------------------------------------------------------------
1 | # التحقق من الإيميل
2 |
3 | - [المقدمة](#introduction)
4 | - [تحضير النموذج](#model-preparation)
5 | - [تحضير قاعدة البيانات](#database-preparation)
6 | - [التوجيه](#verification-routing)
7 | - [إنذار التحقق من الإيميل](#the-email-verification-notice)
8 | - [معالج التحقق من الإيميل](#the-email-verification-handler)
9 | - [إعادة إرسال إيميل التحقق](#resending-the-verification-email)
10 | - [حماية المسارات](#protecting-routes)
11 | - [التخصيص](#customization)
12 | - [الأحداث](#events)
13 |
14 |
15 | ## المقدمة
16 |
17 | العديد من تطبيقات الويب تطلب من المستخدمين التحقق من عنوان بريدهم الالكتروني قبل استخدام التطبيق
18 |
19 | تجبرك لإعادة تحقيق هذه الميزة لكل تطبيق تنشئه
20 |
21 | تؤمن لارافل خدمة مضمنة معها لإرسال إيميل التحقق
22 |
23 |
24 | ### تحضير النموذج
25 |
26 | قبل البدء تحقق أن النموذج`App\Models\User` يحقق العقد `Illuminate\Contracts\Auth\MustVerifyEmail`
27 |
55 | ### تحضير قاعدة البيانات
56 |
57 | يجب أن يحوي جدول المستخدمين `users` حقل `email_verified_at` لتخزين تاريخ ووقت التحقق من إيميل المستخدم
58 |
59 | افتراضياً يحتوي تهجير جدول المستخدمين المضمن في لارافل هذا الحقل بالفعل لذلك نحتاج فقط لتشغيل تهجير قاعدة البيانات
60 |
61 | ```shell
62 | php artisan migrate
63 | ```
64 |
65 |
66 | ## التوجيه
67 |
68 | يجب تعريف ثلاث مسارات لتحقق من الإيميل
69 |
70 | المسار الأول لعرض ملاحظة للمستخدم للضغط على رابط التحقق من الإيميل الذي أرسلته لارافل للمستخدم بعد التسجيل
71 |
72 | الثاني لمعالجة الطلبات بعد ضغط المستخدم على الرابط
73 |
74 | الثالث لإعادة إرسال رابط تحقق في حال فقدان المستخدم الرابط الأول
75 |
76 |
77 |
78 | ### ملاحظة أو انذار التحقق من الإيميل
79 |
80 | كما ذكرنا سابقاً المسار الأول يعيد واجهة ترشد المستخدم للضغط على إيميل التحقق المرسلة من قبل لارافل بعد عملية التسجيل
81 |
82 | تظهر هذه الواجهة للمستخدم في حال حاول الدخول للتطبيق بدون التحقق من الإيميل
83 |
84 | يُرسل هذا الرابط بشكل ألي للمستخدم طالما حقق النموذج `App\Models\User` الواجهة `MustVerifyEmail`
85 |
86 | Route::get('/email/verify', function () {
87 | return view('auth.verify-email');
88 | })->middleware('auth')->name('verification.notice');
89 |
90 | يجب تسمية المسار الذي أرسل إنذار التحقق من الإيميل `verification.notice`
91 |
92 | من المهم إعطاء هذا الاسم بالضبط ليقوم الكائن الوسيط `verified` بتحويل المستخدم إلى اسم هذا المسار إذا لم يتحقق المستخدم من الإيميل
93 |
94 |
95 | ### معالج التحقق من الإيميل
96 |
97 | يجب تعريف المسار الذي سيعالج الطلبات بعد ضغط المستخدم على رابط التحقق من الإيميل الذي أُرسل له
98 |
99 | اسم هذا المسار `verification.verify`
100 |
101 | وتعيين كائنين وسيطين `auth` و `signed`
102 |
103 |
104 | use Illuminate\Foundation\Auth\EmailVerificationRequest;
105 |
106 | Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
107 | $request->fulfill();
108 |
109 | return redirect('/home');
110 | })->middleware(['auth', 'signed'])->name('verification.verify');
111 |
112 | استخدمنا في هذا المثال `EmailVerificationRequest`
113 |
114 | يأخذ هذا الطلب متغيرين`id` و `hash`
115 |
116 | نقوم بنداء الطريقة `fulfill` هذه الطريقة تقوم بنداء الطريقة `markEmailAsVerified` على المستخدم المسجل وترسل الحدث `Illuminate\Auth\Events\Verified`
117 |
118 | الطريقة `markEmailAsVerified` متاحة مع النموذج الافتراضي `App\Models\User` عن طريق الصف الأساسي `Illuminate\Foundation\Auth\User`
119 |
120 | اذا تم التحقق من الايميل يمكنك توجيه المستخدم للصفحة التي تريدها
121 |
122 |
123 | ### إعادة إرسال التحقق من الايميل
124 |
125 | أحيانا يفقد المستخدم ايميل التحقق يجب تحيد مسار يسمح بإعادة إرسال الايميل لذلك نستخدم زر إعادة الإرسال ضمن واجهة إنذار التحقق
126 |
127 | [verification notice view](#the-email-verification-notice)
128 | use Illuminate\Http\Request;
129 |
130 | Route::post('/email/verification-notification', function (Request $request) {
131 | $request->user()->sendEmailVerificationNotification();
132 |
133 | return back()->with('message', 'Verification link sent!');
134 | })->middleware(['auth', 'throttle:6,1'])->name('verification.send');
135 |
136 |
137 | ### حماية المسارات
138 |
139 | يسمح الكائن الوسيط [Route middleware](/docs/{{version}}/middleware) للمستخدمين المسجلين بالوصول للمسار المعطى
140 |
141 | اذا تم تسجيل الكائن الوسيط ضمن التطبيق في نواة HTTP
142 |
143 | كل ما عليك فعله ربط الوسيط بالمسار المعرف
144 |
145 | Route::get('/profile', function () {
146 | // Only verified users may access this route...
147 | })->middleware('verified');
148 |
149 | إذا حاول المستخدم غير متحقق من الايميل الوصول إلى مسار يقوم الوسيط بتحويله إلى `verification.notice` [named route](/docs/{{version}}/routing#named-routes)
150 |
151 |
152 | ## التخصيص
153 |
154 |
155 | #### تخصيص التحقق من الايميل
156 |
157 | تسمح لارافل بتخصيص بنية رسالة ايميل التحقق
158 |
159 | مرر closure للطريقة `toMailUsing` الموجودة في `Illuminate\Auth\Notifications\VerifyEmail`
160 |
161 | closure يستقبل نسخة من نموذج الاشعار الذي يرسل اشعار بالرابط الذي يتوجب على المستخدم زيارته ليتم التحقق من الايميل
162 |
163 | closure يعيد نسخة من `Illuminate\Notifications\Messages\MailMessage`
164 |
165 | يجب نداء الطريقة `toMailUsing` من الطريقة `boot` بالصف `App\Providers\AuthServiceProvider`
166 |
167 |
168 | use Illuminate\Auth\Notifications\VerifyEmail;
169 | use Illuminate\Notifications\Messages\MailMessage;
170 |
171 | /**
172 | * Register any authentication / authorization services.
173 | *
174 | * @return void
175 | */
176 | public function boot()
177 | {
178 | // ...
179 |
180 | VerifyEmail::toMailUsing(function ($notifiable, $url) {
181 | return (new MailMessage)
182 | ->subject('Verify Email Address')
183 | ->line('Click the button below to verify your email address.')
184 | ->action('Verify Email Address', $url);
185 | });
186 | }
187 |
188 |
189 |
190 | ## الأحداث
191 |
192 | عند استخدام [Laravel application starter kits](/docs/{{version}}/starter-kits) تقوم لارافل بإرسال Laravel dispatches [events](/docs/{{version}}/events) خلال عملية التحقق من الايميل
193 |
194 | إذا تمت معالجة التحقق من الايميل بشكل يدوي يجب ارسال هذه الأحداث يدويا بعد انتهاء عملية التحقق
195 |
196 | ربط المستمعات لهذه الأحداث في `EventServiceProvider`
197 |
198 | /**
199 | * The event listener mappings for the application.
200 | *
201 | * @var array
202 | */
203 | protected $listen = [
204 | 'Illuminate\Auth\Events\Verified' => [
205 | 'App\Listeners\LogVerifiedUser',
206 | ],
207 | ];
208 |
--------------------------------------------------------------------------------
/views.md:
--------------------------------------------------------------------------------
1 | # الواجهات (Views)
2 |
3 | - [الواجهات (Views)](#الواجهات-views)
4 | - [مقدمة](#مقدمة)
5 | - [إنشاء وتقديم الواجهات](#إنشاء-وتقديم-الواجهات)
6 | - [إنشاء أوّل واجهة متاحة](#إنشاء-أوّل-واجهة-متاحة)
7 | - [تحديد إن كانت الواجهة موجودة](#تحديد-إن-كانت-الواجهة-موجودة)
8 | - [تمرير البيانات للواجهات](#تمرير-البيانات-للواجهات)
9 | - [مشاركة البيانات مع جميع الواجهات](#مشاركة-البيانات-مع-جميع-الواجهات)
10 | - [مؤلّفو الواجهات (View Composers)](#مؤلّفو-الواجهات-view-composers)
11 | - [إرفاق المُؤلّف مع عدّة واجهات](#إرفاق-المُؤلّف-مع-عدّة-واجهات)
12 | - [مُنشؤو الواجهات (View creators)](#مُنشؤو-الواجهات-view-creators)
13 | - [تحسين الواجهات](#تحسين-الواجهات)
14 |
15 |
16 | ## مقدمة
17 |
18 | بالطبع ، ليس من العملي إرجاع سلاسل مستندات HTML بالكامل مباشرةً من المسارات (paths) والمتحكمات الخاصة بك (controllers). لحسن الحظ ، توفر الواجهات طريقة مناسبة لوضع كل HTML في ملفات منفصلة. تفصل الواجهات منطق وحدة التحكم / منطق التطبيق عن منطق عرضك التقديمي (presentation logic) ويتم تخزين الواجهات في المجلد `resources/view`. قد تشبه الواجهة البسيطة المثال التالي:
19 |
20 | ```blade
21 |
22 |
23 |
24 |
25 | Hello, {{ $name }}
26 |
27 |
28 | ```
29 | نظراً لأن هذه الواجهة مخزنة في `resources/views/greeting.blade.php` ، يمكننا ارجاعها باستخدام المساعد العام `view` مثل:
30 | ```php
31 | Route::get('/', function () {
32 | return view('greeting', ['name' => 'James']);
33 | });
34 | ```
35 |
36 | > ملاحظة: هل تبحث عن مزيد من المعلومات حول كيفية كتابة قوالب Blade؟ ألق نظرة على [توثيق Blade](/docs/{{version}}/blade) الكامل للبدء.
37 |
38 |
39 |
40 | ## إنشاء وتقديم الواجهات
41 | يمكنك إنشاء واجهة عن طريق وضع ملف بامتداد `.blade.php` في مجلد `resources/views` في تطبيقك. يخبر الامتداد `.blade.php` إطار العمل (framework) بأن الملف يحتوي على [قالب Blade](/docs/{{version}}/blade). تحتوي قوالب الBlade على HTML بالإضافة إلى مجلدات Blade التي تتيح لك محاكاة القيم بسهولة وإنشاء عبارات "if" والتكرار على البيانات والمزيد.
42 |
43 | بمجرد إنشاء واجهة ، يمكنك إرجاعها من أحد مسارات أو متحكمات في تطبيقك باستخدام المساعد العام `view`:
44 | ```php
45 | Route::get('/', function () {
46 | return view('greeting', ['name' => 'James']);
47 | });
48 |
49 | يمكن أيضاً إرجاع الواجهة عبر الواجهة الساكنة `View`:
50 |
51 | use Illuminate\Support\Facades\View;
52 |
53 | return View::make('greeting', ['name' => 'James']);
54 | ````
55 | كما ترى، يُوافق المّتغيّر الوسيط الأوّل المُمرّر إلى المُساعد view اسم ملف الواجهة في المجلّد resources/views. المتغيّر الوسيط الثاني هو مصفوفة البيانات التي يجب أن تُتاح للواجهة. نقوم في هذه الحالة بتمرير المتغيّر name الذي يُعرض في الواجهة باستخدام [صيغة Blade](/docs/{{version}}/blade).
56 |
57 |
58 |
59 | ### مجلدات الواجهة المتداخلة(Nested)
60 | يمكن أيضاً تضمين (nesting) الواجهات ضمن مُجلّدات فرعية من المُجلّد `resources/views`. يمكن استخدام الترميز "نقطة" للإشارة للعروض المتداخلة (nested). مثلا، إن خُزّن عرضك في `resources/views/admin/profile.blade.php`، يمكن ارجاعه من أحد مسارات/ متحكمات تطبيقك على النحو التالي:
61 | ```php
62 | return view('admin.profile', $data);
63 | ```
64 | > ملاحظة: يجب ألا تحتوي مجلدات الواجهة على نقطة `.`
65 |
66 |
67 |
68 | ### إنشاء أوّل واجهة متاحة
69 |
70 | يمكنك إنشاء `الواجهة` الأولى في مصفوفة معيّنة من الواجهات باستخدام التابع `first`. يُفيدك هذا إن سمح تطبيقك أو حزمتك بتخصيص الواجهات أو إعادة تعريفها (overwritten):
71 |
72 | use Illuminate\Support\Facades\View;
73 |
74 | return View::first(['custom.admin', 'admin'], $data);
75 |
76 |
77 |
78 | ### تحديد إن كانت الواجهة موجودة
79 |
80 | إن كنت بحاجة لتحديد إن كانت الواجهة موجودة، يمكنك استخدام الواجهة الساكنة View (أي `View` facade). سيرد التابع `exists` بالقيمة true إن وُجدت الواجهة:
81 | ```php
82 | use Illuminate\Support\Facades\View;
83 |
84 | if (View::exists('emails.customer')) {
85 | //
86 | }
87 | ```
88 |
89 |
90 | ## تمرير البيانات للواجهات
91 |
92 | كما رأيت في الأمثلة السابقة، يمكنك تمرير مصفوفة من البيانات للواجهات لجعل تلك البيانات متوفرة للواجهة:
93 | ```php
94 | return view('greetings', ['name' => 'Victoria']);
95 | ```
96 | عند تمرير المعلومات بهذه الطريقة ، يجب أن تكون البيانات مصفوفة من الأزواج مفتاح / قيمة (key/value). بعد تمرير البيانات للواجهة
97 | يمكنك الوصول لكل قيمة باستخدام مفتاحها المُوافق داخل واجهتك، مثل `;php echo $key ?>`. كبديل لتمرير مصفوفة كاملة من البيانات إلى دالّة المُساعد `view،` يمكنك استخدام التابع `with` لإضافة أجزاء منفردة من البيانات للواجهة. يرجع التابع `with` نسخة من كائن الواجهة (view object) بحيث يمكنك متابعة تسلسل التوابع قبل إرجاع الواجهة:
98 | ```php
99 | return view('greeting')
100 | ->with('name', 'Victoria')
101 | ->with('occupation', 'Astronaut');
102 | ```
103 |
104 |
105 |
106 | ### مشاركة البيانات مع جميع الواجهات
107 | في بعض الأحيان ، قد تحتاج إلى مشاركة البيانات مع جميع واجهات تطبيقك.
108 | يمكنك استخدام التابع `share` من واجهة العرض الساكنة (view facade) للقيام بذلك. عادة، عليك وضع نداءات التابع `share` داخل تابع مقدّم الخدمات `boot`. لك حريّة إضافتها إلى `App\Providers\AppServiceProvider class` أو إنشاء مُقدّم خدمة منفصل لإيوائها:
109 |
110 | ```php
111 |
141 |
142 | ## مؤلّفو الواجهات (View Composers)
143 | مُؤلّفو الواجهات هم عمليات نداء (callbacks) أو دوال أصناف (class methods) تُستدعى عند عرض الواجهة. إذا كانت لديك بيانات تريد ربطها بواجهة في كل مرة يتم فيها عرض هذا الواجهة ، فيمكن أن يساعدك مؤلف الواجهة في تنظيم هذا المنطق في مكان واحد. قد يكون مؤلفو الواجهة ذو فائدة بشكل خاص إذا تم إرجاع نفس الواجهة من خلال مسارات أو متحكمات متعددة داخل تطبيقك وتحتاج دائماً إلى جزء معين من البيانات.
144 | عادةً ، سيتم تسجيل مؤلفي الواجهات في أحد [مزودي الخدمة](/docs/{{version}}/providers) لتطبيقك. في هذا المثال ، سنفترض أننا أنشأنا `App\Providers\ViewServiceProvider` جديدًا لإيواء هذا المنطق.
145 | سنستخدم التابع `composer` للواجهة الساكنة View لتسجيل مؤلف الواجهة تذكر أن Laravel لا يحتوي على مجلّد افتراضي لمؤلّفي الواجهات المعتمدة على الأصناف (class based). لديك حريّة تنظيمها كما شئت. على سبيل المثال ، يمكنك إنشاء دليل `app/View/Composers` لإيواء جميع مؤلفي واجهات تطبيقك:
146 | ```php
147 | ملاحظة: تذكر أنه إن أنشأت مقدّم خدمات جديد لاحتواء تسجيلات مؤلف واجهاتك ستحتاج لإضافة مُقدّم الخدمات إلى مصفوفة `providers` في ملف الإعدادات `config/app.php.`.
187 |
188 | بعد تسجيلنا للمؤلّف سيُنفّذ الآن سينفذ التابع `compose` من الصنف `App\View\Composers\ProfileComposer` في كل مرة يتم عرض واجهة `profile`. لذا فلنتعرف على صنف المؤلف:
189 | ```php
190 | users = $users;
216 | }
217 |
218 | /**
219 | * إربط البيانات بالواجهة
220 | *
221 | * @param \Illuminate\View\View $view
222 | * @return void
223 | */
224 | public function compose(View $view)
225 | {
226 | $view->with('count', $this->users->count());
227 | }
228 | }
229 |
230 | ```
231 | كما ترى، يُستبين كل مؤلّفو الواجهة عبر [حاوي الخدمات](/docs/{{version}}/container)، لذا تستطيع التلميح على نوع أي إعتماديّة تحتاجها داخل تابع بناء المؤلّف (composer's constructor).
232 |
233 |
234 |
235 |
236 | #### إرفاق المُؤلّف مع عدّة واجهات
237 | يمكنك إرفاق أحد مؤلّفي الواجهة بعدة واجهات مرّة واحدة بتمرير مصفوفة من الواجهات كالمُتغيّر الوسيط الأوّل للتابع `composer`:
238 | ```php
239 | use App\Views\Composers\MultiComposer;
240 |
241 | View::composer(
242 | ['profile', 'dashboard'],
243 | MultiComposer::class
244 | );
245 | ```
246 | يقبل التابع `composer` أيضاً الحرف `*` كحرف بدل خاص (wildcard)، مما يتيح لك إرفاق مُؤلّف لكل الواجهات:
247 | ```php
248 |
249 | View::composer('*', function ($view) {
250 | //
251 | });
252 | ```
253 |
254 |
255 |
256 | ### مُنشؤو الواجهات (View creators)
257 | يشبه مُنشؤو الواجهات مؤلّفي الواجهات جداً؛ مع فارق أنّها تُنفّذ مباشرة بعد إنشاء نسخة (instantiating) الواجهة بدلاً من الانتظار حتى ينتهي عرضه. لتسجيل منشئ واجهة استخدم التابع `creator`:
258 | ```php
259 | use App\View\Creators\ProfileCreator;
260 | use Illuminate\Support\Facades\View;
261 |
262 | View::creator('profile', ProfileCreator::class);
263 | ```
264 |
265 |
266 |
267 | ## تحسين الواجهات
268 |
269 | بشكل افتراضي ، يتم ترجمة واجهات قالب Blade عند الطلب. عندما يتم تنفيذ طلب الذي يعرض واجهة ، سيحدد Laravel ما إذا كانت هناك نسخة مترجمة موجودة من الواجهة. إذا كان الملف موجوداً ، فسيحدد Laravel بعد ذلك ما إذا كان الواجهة الغير مترجمة قد تم تعديلها مؤخراً عن الواجهة المترجمة. إذا كانت الواجهة المترجمة إما غير موجود ، أو تم تعديل الواجهة الغير مترجمة ، فسيعيد Laravel ترجمة الواجهة.
270 |
271 | قد يكون ترجمة الواجهات أثناء الطلب تأثير سلبي بسيط على الأداء ، لذلك يوفر Laravel أمر `view: cache` Artisan لإجراء ترجمة مسبقة لجميع الواجهات التي يستخدمها تطبيقك. لزيادة الأداء ، قد ترغب في تشغيل هذا الأمر كجزء من عملية النشر الخاصة بك:
272 |
273 | ```shell
274 | php artisan view:cache
275 | ```
276 | يمكنك استخدام الأمر `view: clear` لمسح ذاكرة التخزين المؤقت للواجهة:
277 |
278 | ```shell
279 | php artisan view:clear
280 | ```
--------------------------------------------------------------------------------