├── .docs └── .gitignore ├── index └── .gitignore ├── tests ├── data │ ├── .docs │ │ ├── .gitignore │ │ └── 10.x │ │ │ ├── artisan.md │ │ │ └── validation.md │ ├── index │ │ └── .gitignore │ ├── styles.php │ ├── search │ │ └── option-shortcuts.html │ └── artisan.ladoc ├── TestCase.php ├── bootstrap.php ├── Unit │ ├── TermwindTest.php │ ├── Process │ │ └── ProcessFactoryTest.php │ ├── CheckTest.php │ ├── SectionTest.php │ ├── StylesTest.php │ ├── Enum │ │ └── VersionTest.php │ ├── RepositoryTest.php │ ├── Action │ │ ├── SectionQueryActionTest.php │ │ ├── SectionListActionTest.php │ │ ├── ListActionTest.php │ │ └── SectionIndexActionTest.php │ ├── Index │ │ ├── ItemListTest.php │ │ ├── RenderTest.php │ │ ├── IndexListTest.php │ │ └── IndexManagerTest.php │ ├── TermwindFormatterTest.php │ ├── InputResolverTest.php │ ├── SplitterTest.php │ └── FileManagerTest.php └── Feature │ └── MainCommandTest.php ├── phpstan.neon ├── art └── example.png ├── styles.php ├── .gitignore ├── src ├── Exception │ ├── FileManagerException.php │ └── LadocException.php ├── Formatter │ ├── FormatterInterface.php │ └── TermwindFormatter.php ├── Process │ ├── Process.php │ ├── ProcessFactory.php │ └── ProcessInterface.php ├── Action │ ├── ActionInterface.php │ ├── SectionListAction.php │ ├── ListAction.php │ ├── SectionIndexAction.php │ └── SectionQueryAction.php ├── Section.php ├── Styles.php ├── Termwind.php ├── Index │ ├── ItemList.php │ ├── Render.php │ ├── IndexList.php │ └── IndexManager.php ├── Check.php ├── Enum │ └── Version.php ├── Repository.php ├── InputResolver.php ├── Command │ └── MainCommand.php ├── Splitter.php └── FileManager.php ├── .github └── workflows │ ├── docker-built.yml │ └── test.yml ├── Dockerfile ├── bootstrap.php ├── bin └── ladoc ├── phpunit.xml ├── LICENSE.md ├── composer.json └── README.md /.docs/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /index/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /tests/data/.docs/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore -------------------------------------------------------------------------------- /tests/data/index/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: 8 3 | paths: 4 | - src 5 | - tests -------------------------------------------------------------------------------- /art/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/millancore/ladoc/HEAD/art/example.png -------------------------------------------------------------------------------- /styles.php: -------------------------------------------------------------------------------- 1 | 'bg-teal-700 px-1', 5 | 'inline-code' => 'bg-gray-700', 6 | ]; -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | 'bg-teal-500 px-1', 5 | 'inline-code' => 'bg-gray-700', 6 | ]; 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .phpunit.result.cache 2 | .phpunit.cache 3 | .php-cs-fixer.cache 4 | .idea 5 | .github 6 | coverage 7 | vendor 8 | version.php 9 | user-styles.php -------------------------------------------------------------------------------- /src/Exception/FileManagerException.php: -------------------------------------------------------------------------------- 1 | Option Shortcuts

3 |

To assign a shortcut when defining an option, you may specify it before the option name and use a | delimiter to separate the shortcut from the full option name:

4 | email:send {user} {--Q|queue} 5 | 6 | -------------------------------------------------------------------------------- /src/Action/ActionInterface.php: -------------------------------------------------------------------------------- 1 | $query 9 | * @param array $options 10 | * @return string 11 | */ 12 | public function execute(array $query, array $options = []): string; 13 | } 14 | -------------------------------------------------------------------------------- /src/Process/ProcessFactory.php: -------------------------------------------------------------------------------- 1 | $parameters 9 | * @return ProcessInterface 10 | */ 11 | public function newProcess(array $parameters): ProcessInterface 12 | { 13 | return new Process($parameters); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /.github/workflows/docker-built.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | 17 | - run: docker build -t millancore/ladoc . 18 | - run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} 19 | - run: docker push millancore/ladoc 20 | -------------------------------------------------------------------------------- /src/Process/ProcessInterface.php: -------------------------------------------------------------------------------- 1 | $env 10 | * @return int 11 | */ 12 | public function run(callable $callback = null, array $env = []): int; 13 | 14 | public function getOutput(): string; 15 | 16 | public function isSuccessful(): bool; 17 | 18 | public function getErrorOutput(): string; 19 | } 20 | -------------------------------------------------------------------------------- /src/Section.php: -------------------------------------------------------------------------------- 1 | $articles 15 | */ 16 | public function __construct( 17 | public string $name, 18 | public IndexList $indexList, 19 | public array $articles 20 | ) { 21 | // 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM composer:2.5.8 AS composer 2 | 3 | WORKDIR /app 4 | 5 | COPY composer.json composer.json 6 | COPY composer.lock composer.lock 7 | 8 | RUN composer install --no-dev --no-scripts --no-interaction --no-progress --prefer-dist 9 | 10 | FROM php:8.2-cli-alpine3.18 11 | 12 | RUN apk add --no-cache git grep 13 | 14 | WORKDIR /app 15 | 16 | COPY . . 17 | COPY --from=composer /app/vendor vendor 18 | 19 | ENV TERM=xterm-256color 20 | 21 | RUN ln -s /app/bin/ladoc /usr/local/bin/ladoc 22 | RUN ln -s /app/bin/ladoc /usr/local/bin/zz 23 | -------------------------------------------------------------------------------- /bootstrap.php: -------------------------------------------------------------------------------- 1 | $styles 9 | */ 10 | public function __construct(public array $styles) 11 | { 12 | // 13 | } 14 | 15 | public function get(string $name): string 16 | { 17 | return $this->styles[$name]; 18 | } 19 | 20 | /** 21 | * @return array 22 | */ 23 | public function all(): array 24 | { 25 | return $this->styles; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /bin/ladoc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | add($searchCommand); 23 | $application->setDefaultCommand($searchCommand->getName(), true); 24 | 25 | $application->run(); -------------------------------------------------------------------------------- /tests/Unit/TermwindTest.php: -------------------------------------------------------------------------------- 1 | 'bg-teal-500 px-1', 19 | 'inline-code' => 'bg-gray-500', 20 | ])); 21 | 22 | $this->assertTrue($termwind->loadStyles()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Setup PHP 21 | uses: shivammathur/setup-php@v2 22 | with: 23 | php-version: '8.2' 24 | 25 | - name: Install dependencies 26 | run: composer install --prefer-dist --no-progress 27 | 28 | - name: Run test suite 29 | run: composer run test 30 | -------------------------------------------------------------------------------- /src/Action/SectionListAction.php: -------------------------------------------------------------------------------- 1 | indexManager->getSectionIndex($this->section); 22 | 23 | return Render::sectionIndexList($indexSection); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Action/ListAction.php: -------------------------------------------------------------------------------- 1 | indexManager->getMainIndex(); 21 | 22 | if(isset($options['letter'])) { 23 | $mainList = $mainList->filterByLetter($options['letter']); 24 | } 25 | 26 | return Render::mainIndexList($mainList); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /tests/Unit/Process/ProcessFactoryTest.php: -------------------------------------------------------------------------------- 1 | newProcess(['ls', '-la']); 19 | 20 | $this->assertInstanceOf(ProcessInterface::class, $process); 21 | $this->assertInstanceOf(Process::class, $process); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /tests/Unit/CheckTest.php: -------------------------------------------------------------------------------- 1 | getLastVersion(); 17 | 18 | $this->assertMatchesRegularExpression('/^v\d+\.\d+\.\d+$/', (string) $version); 19 | } 20 | 21 | public function test_it_can_compare_local_version_with_tag_version_from_github_api(): void 22 | { 23 | $check = new Check(); 24 | $version = $check->isLastVersion('0.0.0'); 25 | 26 | $this->assertFalse($version); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/Termwind.php: -------------------------------------------------------------------------------- 1 | styles->all(); 21 | 22 | foreach ($styles as $name => $style) { 23 | style($name)->apply($style); 24 | } 25 | 26 | return true; 27 | } 28 | 29 | 30 | /** 31 | * @codeCoverageIgnore 32 | */ 33 | public function render(string $html): void 34 | { 35 | $this->loadStyles(); 36 | render(sprintf('
%s
', $html)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /tests/Unit/SectionTest.php: -------------------------------------------------------------------------------- 1 | 'content-1', 19 | 'article-2' => 'content-2', 20 | ]); 21 | 22 | $this->assertSame('title', $section->name); 23 | $this->assertInstanceOf(IndexList::class, $section->indexList); 24 | $this->assertSame([ 25 | 'article-1' => 'content-1', 26 | 'article-2' => 'content-2', 27 | ], $section->articles); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/Index/ItemList.php: -------------------------------------------------------------------------------- 1 | children === null) { 20 | return false; 21 | } 22 | 23 | return $this->children->isEmpty() === false; 24 | } 25 | 26 | 27 | /** 28 | * @return array 29 | */ 30 | public function toArray(): array 31 | { 32 | return [ 33 | 'title' => $this->title, 34 | 'anchor' => $this->anchor, 35 | 'child' => $this->children?->toArray() 36 | ]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | 20 | src 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /tests/Unit/StylesTest.php: -------------------------------------------------------------------------------- 1 | 'bg-teal-500 px-1', 17 | 'inline-code' => 'bg-gray-500', 18 | ]); 19 | 20 | $this->assertEquals('bg-teal-500 px-1', $styles->get('title')); 21 | $this->assertEquals('bg-gray-500', $styles->get('inline-code')); 22 | } 23 | 24 | public function test_it_can_get_all_styles(): void 25 | { 26 | $styles = new Styles([ 27 | 'title' => 'bg-teal-500 px-1', 28 | 'inline-code' => 'bg-gray-500', 29 | ]); 30 | 31 | $this->assertEquals([ 32 | 'title' => 'bg-teal-500 px-1', 33 | 'inline-code' => 'bg-gray-500', 34 | ], $styles->all()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tests/Unit/Enum/VersionTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('11.x', Version::getLatestVersion()->value); 16 | } 17 | 18 | public function test_it_can_return_version_from_value(): void 19 | { 20 | $this->assertEquals('10.x', Version::fromValue('10.x')->value); 21 | $this->assertEquals('10.x', Version::fromValue(10)->value); 22 | $this->assertEquals('10.x', Version::fromValue(10.0)->value); 23 | $this->assertEquals('6.x', Version::fromValue(6)->value); 24 | $this->assertEquals('5.2', Version::fromValue(5.2)->value); 25 | } 26 | 27 | public function test_error_try_get_invalid_version(): void 28 | { 29 | $this->expectException(\InvalidArgumentException::class); 30 | Version::fromValue('invalid'); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Juan Millan 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. 22 | -------------------------------------------------------------------------------- /src/Check.php: -------------------------------------------------------------------------------- 1 | getLastVersion(); 15 | } catch (Throwable) { 16 | // Try next time 17 | return true; 18 | } 19 | 20 | if (!$lastVersion) { 21 | return true; 22 | } 23 | 24 | return $currentVersion === $lastVersion; 25 | } 26 | 27 | 28 | public function getLastVersion(): ?string 29 | { 30 | $ch = curl_init(); 31 | 32 | curl_setopt($ch, CURLOPT_URL, self::API_URL_TAGS . '?per_page=1'); 33 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 34 | curl_setopt($ch, CURLOPT_USERAGENT, 'Ladoc'); 35 | $response = curl_exec($ch); 36 | curl_close($ch); 37 | 38 | if (!$response) { 39 | return null; 40 | } 41 | 42 | $tags = json_decode((string)$response, true); 43 | 44 | return $tags[0]['name']; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Unit/RepositoryTest.php: -------------------------------------------------------------------------------- 1 | removeDocDirectory(); 28 | 29 | $processFactory = $this->createMock(ProcessFactory::class); 30 | 31 | $process = $this->createMock(Process::class); 32 | $process->method('run')->willReturn(1); 33 | 34 | $process->method('isSuccessful')->willReturn(true); 35 | 36 | $processFactory->method('newProcess')->willReturn($process); 37 | 38 | $repository = new Repository($fileManager, $processFactory); 39 | $repository->check(); 40 | 41 | $this->assertDirectoryExists($fileManager->getDocPath()); 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /tests/Unit/Action/SectionQueryActionTest.php: -------------------------------------------------------------------------------- 1 | createMock(IndexManager::class); 19 | $processFactory = $this->createMock(ProcessFactory::class); 20 | 21 | $indexManager->method('getSectionPath')->willReturn('/tmp'); 22 | 23 | $process = $this->createMock(Process::class); 24 | $process->method('run')->willReturn(1); 25 | $process->method('getOutput')->willReturn( 26 | ROOT_TEST. '/data/search/option-shortcuts.html' 27 | ); 28 | 29 | $processFactory->method('newProcess')->willReturn($process); 30 | 31 | $action = new SectionQueryAction($indexManager, $processFactory, 'section'); 32 | 33 | $content = $action->execute(['option', 'shortcuts']); 34 | $this->assertStringContainsString('

Option Shortcuts

', $content); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/Action/SectionIndexAction.php: -------------------------------------------------------------------------------- 1 | $query 23 | * @param array $options 24 | * @return string 25 | * @throws FileManagerException 26 | */ 27 | public function execute(array $query, array $options = []): string 28 | { 29 | $section = $this->indexManager->getSectionIndex($this->section); 30 | 31 | $element = $section->getNestedItems( 32 | array_map(fn ($item) => (int) $item, $query) 33 | ); 34 | 35 | $list = Render::sectionIndexList($element->children ?? new IndexList()); 36 | $article = $this->indexManager->getArticle($this->section, $element->anchor); 37 | 38 | $output = $article; 39 | 40 | if ($list !== '') { 41 | $output .= '
' . $list; 42 | } 43 | 44 | return $output; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Enum/Version.php: -------------------------------------------------------------------------------- 1 | = 6) { 41 | $version = $version . '.x'; 42 | } 43 | 44 | foreach (self::cases() as $case) { 45 | if($case->value === (string) $version) { 46 | return $case; 47 | } 48 | } 49 | 50 | throw new InvalidArgumentException(sprintf('Version %s not found', $version)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/Action/SectionQueryAction.php: -------------------------------------------------------------------------------- 1 | $query 22 | * @param array $options 23 | * @return string 24 | */ 25 | public function execute(array $query, array $options = []): string 26 | { 27 | $sectionPath = $this->indexManager->getSectionPath($this->section); 28 | 29 | $process = $this->processFactory->newProcess(['grep', 30 | '-rl', 31 | $sectionPath, 32 | '--include=*.html', 33 | '-ie', 34 | implode(' ', $query) 35 | ]); 36 | 37 | $process->run(); 38 | 39 | $output = explode("\n", $process->getOutput()); 40 | $output = array_filter($output); 41 | 42 | $output = array_reverse($output); 43 | 44 | $content = ''; 45 | foreach ($output as $file) { 46 | $content .= file_get_contents($file); 47 | } 48 | 49 | return $content; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/Unit/Action/SectionListActionTest.php: -------------------------------------------------------------------------------- 1 | createMock(IndexManager::class); 23 | 24 | $sectionList = new IndexList('Artisan'); 25 | $sectionList->attach(new ItemList('Introduction', 'artisan-intro', new IndexList())); 26 | $sectionList->attach( 27 | new ItemList( 28 | 'Commands', 29 | 'artisan-commands', 30 | (new IndexList())->attach(new ItemList('Make Command', 'artisan-make-command')) 31 | ) 32 | ); 33 | 34 | $indexManager->method('getSectionIndex') 35 | ->willReturn($sectionList); 36 | 37 | $listAction = new SectionListAction($indexManager, 'artisan'); 38 | 39 | $html = $listAction->execute([], []); 40 | 41 | $this->assertIsString($html); 42 | $this->assertEquals('

Artisan

  • [0] Introduction
  • [1] Commands (+)
', $html); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/Index/Render.php: -------------------------------------------------------------------------------- 1 | getName()) { 13 | $html .= sprintf('

%s

', $indexList->getName()); 14 | } 15 | 16 | $html .= '
    '; 17 | foreach ($indexList->all() as $index => $item) { 18 | $html .= '
  • '; 19 | $html .= sprintf('[%d] %s (%s)', $index, $item->title, $item->anchor); 20 | $html .= '
  • '; 21 | } 22 | 23 | $html .= '
'; 24 | 25 | return $html; 26 | } 27 | 28 | public static function sectionIndexList(IndexList $indexList): string 29 | { 30 | if ($indexList->isEmpty()) { 31 | return ''; 32 | } 33 | 34 | $html = ''; 35 | if($indexList->getName()) { 36 | $html .= sprintf('

%s

', $indexList->getName()); 37 | } 38 | 39 | $html .= '
    '; 40 | foreach ($indexList->all() as $index => $item) { 41 | $html .= '
  • '; 42 | 43 | $children = ''; 44 | if ($item->hasChildren()) { 45 | $children = '(+)'; 46 | } 47 | 48 | $html .= sprintf('[%d] %s %s', $index, $item->title, $children); 49 | $html .= '
  • '; 50 | } 51 | 52 | $html .= '
'; 53 | 54 | return $html; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/Repository.php: -------------------------------------------------------------------------------- 1 | getDir()); 24 | 25 | if (!$exist) { 26 | $this->createVersionDirectory(); 27 | $this->download(); 28 | } 29 | } 30 | 31 | private function getDir(): string 32 | { 33 | return $this->fileManager->getDocPath(); 34 | } 35 | 36 | 37 | private function createVersionDirectory(): void 38 | { 39 | $this->fileManager->createDirectory($this->getDir()); 40 | } 41 | 42 | private function download(): void 43 | { 44 | $command = [ 45 | 'git', 46 | 'clone', 47 | '--branch', 48 | $this->fileManager->getVersion()->value, 49 | self::REPO_URL, 50 | $this->fileManager->getDocPath(), 51 | ]; 52 | 53 | $process = $this->processFactory->newProcess($command); 54 | $process->run(); 55 | 56 | if (!$process->isSuccessful()) { 57 | throw new RuntimeException($process->getErrorOutput()); 58 | } 59 | 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "millancore/ladoc", 3 | "description": "Console tool for explore Laravel Documentation", 4 | "keywords": ["laravel", "php", "documentation", "console", "cli", "tool"], 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Juan Millan", 9 | "email": "juanes14569@gmail.com" 10 | } 11 | ], 12 | "bin": [ 13 | "bin/ladoc" 14 | ], 15 | "autoload": { 16 | "psr-4": { 17 | "Ladoc\\" : "src/" 18 | } 19 | }, 20 | "autoload-dev": { 21 | "psr-4": { 22 | "Ladoc\\Tests\\" : "tests/" 23 | } 24 | }, 25 | "minimum-stability": "stable", 26 | "prefer-stable": true, 27 | "require": { 28 | "php": "^8.2", 29 | "ext-dom": "*", 30 | "ext-curl": "*", 31 | "ext-libxml": "*", 32 | "league/commonmark": "^2.4", 33 | "nunomaduro/termwind": "^1.15", 34 | "symfony/process": "^6.3", 35 | "symfony/console": "^6.3" 36 | }, 37 | "require-dev": { 38 | "phpunit/phpunit": "^10.2", 39 | "symfony/var-dumper": "^6.3", 40 | "friendsofphp/php-cs-fixer": "^3.20", 41 | "phpstan/phpstan": "^1.10" 42 | }, 43 | "scripts": { 44 | "test": "phpunit", 45 | "coverage": "phpunit --coverage-html coverage", 46 | "cs": "php-cs-fixer fix src --rules=@PSR12 --dry-run --diff", 47 | "cs-fix": "php-cs-fixer fix src --rules=@PSR12", 48 | "phpstan": "phpstan analyse --no-progress --level=8 src tests" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Formatter/TermwindFormatter.php: -------------------------------------------------------------------------------- 1 | ]*>.*?<\/style>/is', '', $html) ?? ''; 12 | } 13 | 14 | public function setTitleStyles(string $styles, string $html): string 15 | { 16 | $el = sprintf('

$1

', $styles); 17 | return preg_replace('/]*>(.*?)<\/h\d>/i', $el, $html) ?? ''; 18 | } 19 | 20 | public function setInlineCodeStyles(string $styles, string $html): string 21 | { 22 | $el = sprintf('$1', $styles); 23 | return preg_replace('/]*>(.*?)<\/code>/i', $el, $html) ?? ''; 24 | } 25 | 26 | public function removePreTags(string $html): string 27 | { 28 | return str_replace(['
','
'], '', $html); 29 | } 30 | 31 | public function removeConflictClasses(string $html): string 32 | { 33 | return str_replace([ 34 | 'content-list', 35 | 'collection-method-list' 36 | ], '', $html); 37 | } 38 | 39 | public function format(string $html): string 40 | { 41 | $html = $this->removeStyleBlocks($html); 42 | $html = $this->setTitleStyles('title', $html); 43 | $html = $this->setInlineCodeStyles('inline-code', $html); 44 | $html = $this->removeConflictClasses($html); 45 | $html = $this->removePreTags($html); 46 | 47 | return $html; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /tests/Unit/Index/ItemListTest.php: -------------------------------------------------------------------------------- 1 | assertSame('title', $item->title); 20 | $this->assertSame('anchor', $item->anchor); 21 | $this->assertInstanceOf(IndexList::class, $item->children); 22 | } 23 | 24 | public function test_it_can_validate_if_has_children(): void 25 | { 26 | $item = new ItemList( 27 | 'title', 28 | 'anchor', 29 | (new IndexList())->attach(new ItemList('child title', 'anchor')) 30 | ); 31 | 32 | $this->assertTrue($item->hasChildren()); 33 | } 34 | 35 | public function test_it_can_get_nested_item_as_array(): void 36 | { 37 | $indexList = new IndexList(); 38 | $indexList->attach(new ItemList('child title', 'anchor', new IndexList())); 39 | 40 | $item = new ItemList('title', 'anchor', $indexList); 41 | 42 | $this->assertSame([ 43 | 'title' => 'title', 44 | 'anchor' => 'anchor', 45 | 'child' => [ 46 | [ 47 | 'title' => 'child title', 48 | 'anchor' => 'anchor', 49 | 'child' => [] 50 | ] 51 | ] 52 | ], $item->toArray()); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /tests/Unit/Index/RenderTest.php: -------------------------------------------------------------------------------- 1 | attach(new ItemList('title one', 'anchor-one')); 22 | $indexList->attach(new ItemList('title two', 'anchor-two')); 23 | $indexList->attach(new ItemList('title three', 'anchor-three')); 24 | 25 | $this->assertSame( 26 | '

Test List

  • [0] title one (anchor-one)
  • [1] title two (anchor-two)
  • [2] title three (anchor-three)
', 27 | Render::mainIndexList($indexList) 28 | ); 29 | } 30 | 31 | public function test_it_can_render_section_list(): void 32 | { 33 | $indexList = new IndexList('Test Section List'); 34 | 35 | $indexList->attach(new ItemList('title one', 'anchor-one')); 36 | $indexList->attach( 37 | new ItemList( 38 | 'title two', 39 | 'anchor-two', 40 | (new IndexList()) 41 | ->attach(new ItemList('child title', 'anchor')) 42 | ) 43 | ); 44 | $indexList->attach(new ItemList('title three', 'anchor-three')); 45 | 46 | $this->assertSame( 47 | '

Test Section List

  • [0] title one
  • [1] title two (+)
  • [2] title three
', 48 | Render::sectionIndexList($indexList) 49 | ); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /tests/Unit/Action/ListActionTest.php: -------------------------------------------------------------------------------- 1 | createMock(IndexManager::class); 24 | 25 | $mainList = new IndexList('Main List'); 26 | $mainList->attach(new ItemList('Artisan Console', 'artisan')); 27 | $mainList->attach(new ItemList('Validation', 'validation')); 28 | 29 | $indexManager->method('getMainIndex') 30 | ->willReturn($mainList); 31 | 32 | $listAction = new ListAction($indexManager); 33 | 34 | $html = $listAction->execute([], []); 35 | 36 | $this->assertIsString($html); 37 | $this->assertEquals('

Main List

  • [0] Artisan Console (artisan)
  • [1] Validation (validation)
', $html); 38 | } 39 | 40 | 41 | public function test_it_can_return_main_list_filtered(): void 42 | { 43 | $indexManager = $this->createMock(IndexManager::class); 44 | 45 | $mainList = new IndexList('Main List'); 46 | $mainList->attach(new ItemList('Artisan Console', 'artisan')); 47 | $mainList->attach(new ItemList('Validation', 'validation')); 48 | 49 | $indexManager->method('getMainIndex') 50 | ->willReturn($mainList); 51 | 52 | $listAction = new ListAction($indexManager); 53 | 54 | $html = $listAction->execute([], ['letter' => 'v']); 55 | 56 | $this->assertIsString($html); 57 | $this->assertEquals('

Main List | filter: V

  • [0] Validation (validation)
', $html); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /tests/Unit/TermwindFormatterTest.php: -------------------------------------------------------------------------------- 1 | body { color: red; }

Test

'; 19 | $expected = '

Test

'; 20 | 21 | $this->assertEquals($expected, $formatter->removeStyleBlocks($html)); 22 | } 23 | 24 | 25 | public function test_it_can_set_title_styles(): void 26 | { 27 | $formatter = new TermwindFormatter(); 28 | 29 | $html = '

Test

'; 30 | $expected = '

Test

'; 31 | 32 | $this->assertEquals($expected, $formatter->setTitleStyles('text-2xl font-bold', $html)); 33 | } 34 | 35 | public function test_it_can_set_inline_code_styles(): void 36 | { 37 | $formatter = new TermwindFormatter(); 38 | 39 | $html = 'Test

lorem

extra'; 40 | $expected = 'Test

lorem

extra'; 41 | 42 | $this->assertEquals($expected, $formatter->setInlineCodeStyles('bg-gray-100', $html)); 43 | } 44 | 45 | public function test_it_can_remove_all_pre_tags(): void 46 | { 47 | $formatter = new TermwindFormatter(); 48 | 49 | $html = '
Test

lorem

extra
'; 50 | $expected = 'Test

lorem

extra'; 51 | 52 | $this->assertEquals($expected, $formatter->removePreTags($html)); 53 | } 54 | 55 | public function test_it_can_format_html_document(): void 56 | { 57 | $formatter = new TermwindFormatter(); 58 | 59 | $html = '

Test

Test

lorem

extra
'; 60 | $expected = '

Test

Test

lorem

extra'; 61 | 62 | $this->assertEquals($expected, $formatter->format($html)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tests/Unit/Action/SectionIndexActionTest.php: -------------------------------------------------------------------------------- 1 | createMock(IndexManager::class); 21 | 22 | $indexTest = file_get_contents(ROOT_TEST . '/data/artisan.ladoc'); 23 | 24 | $indexManager->expects($this->once()) 25 | ->method('getSectionIndex') 26 | ->with('artisan') 27 | ->willReturn(unserialize((string) $indexTest)); 28 | 29 | $indexManager->expects($this->once()) 30 | ->method('getArticle') 31 | ->with('artisan', 'input-arrays') 32 | ->willReturn('

Input Arrays

'); 33 | 34 | $action = new SectionIndexAction($indexManager, 'artisan'); 35 | 36 | $output = $action->execute([2, 2]); 37 | 38 | $this->assertStringContainsString('

Input Arrays

', $output); 39 | } 40 | 41 | public function test_it_can_return_with_child_list(): void 42 | { 43 | $indexManager = $this->createMock(IndexManager::class); 44 | 45 | $indexTest = file_get_contents(ROOT_TEST . '/data/artisan.ladoc'); 46 | 47 | $indexManager->expects($this->once()) 48 | ->method('getSectionIndex') 49 | ->with('artisan') 50 | ->willReturn(unserialize((string) $indexTest)); 51 | 52 | $indexManager->expects($this->once()) 53 | ->method('getArticle') 54 | ->with('artisan', 'defining-input-expectations') 55 | ->willReturn('

Defining Input Expectations

'); 56 | 57 | $action = new SectionIndexAction($indexManager, 'artisan'); 58 | 59 | $output = $action->execute([2]); 60 | 61 | $this->assertStringContainsString('

Defining Input Expectations

', $output); 62 | $this->assertStringContainsString('
  • [0] Arguments
  • [1] Options
  • [2] Input Arrays
  • [3] Input Descriptions
', $output); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/InputResolver.php: -------------------------------------------------------------------------------- 1 | $query 23 | * @param array $options 24 | * @return ActionInterface 25 | * @throws FileManagerException 26 | */ 27 | public function resolve( 28 | string|int $section, 29 | array $query = [], 30 | array $options = [] 31 | ): ActionInterface { 32 | if (is_numeric($section)) { 33 | $section = $this->resolveNumericalSection((int) $section, $options); 34 | } 35 | 36 | if ($section === 'list') { 37 | return new Action\ListAction($this->indexManager); 38 | } 39 | 40 | if (empty($query)) { 41 | return new Action\SectionListAction($this->indexManager, $section); 42 | } 43 | 44 | if ($this->queryHasOnlyNumber($query)) { 45 | return new Action\SectionIndexAction($this->indexManager, $section); 46 | } 47 | 48 | return new Action\SectionQueryAction( 49 | $this->indexManager, 50 | new ProcessFactory(), 51 | $section 52 | ); 53 | } 54 | 55 | 56 | /** 57 | * @param int $section 58 | * @param array $option 59 | * @return string 60 | * @throws FileManagerException 61 | */ 62 | private function resolveNumericalSection(int $section, array $option = []): string 63 | { 64 | $mainList = $this->indexManager->getMainIndex(); 65 | 66 | if (isset($option['letter'])) { 67 | $mainList = $this->indexManager->getMainIndex()->filterByLetter($option['letter']); 68 | } 69 | 70 | return $mainList->get($section)->anchor; 71 | } 72 | 73 | 74 | /** 75 | * @param array $query 76 | * @return bool 77 | */ 78 | private function queryHasOnlyNumber(array $query): bool 79 | { 80 | if (empty($query)) { 81 | return false; 82 | } 83 | 84 | return !in_array(false, array_map(fn ($item) => is_numeric($item), $query)); 85 | } 86 | 87 | 88 | } 89 | -------------------------------------------------------------------------------- /tests/Feature/MainCommandTest.php: -------------------------------------------------------------------------------- 1 | removeIndexDirectory(); 36 | } 37 | 38 | /** 39 | * @uses \Ladoc\Action\ListAction 40 | * @uses \Ladoc\Index\IndexList 41 | * @uses \Ladoc\Index\ItemList 42 | * @uses \Ladoc\Index\Render 43 | */ 44 | public function test_it_can_display_main_list(): void 45 | { 46 | $commandTester = $this->getCommandTester(); 47 | 48 | $commandTester->execute([ 49 | 'section' => 'list', 50 | 'query' => [], 51 | '--letter' => 'a', 52 | ]); 53 | 54 | $commandTester->assertCommandIsSuccessful(); 55 | $output = $commandTester->getDisplay(); 56 | 57 | $this->assertStringContainsString('Main List | filter: A', $output); 58 | $this->assertStringContainsString('[0] Artisan Console (artisan)', $output); 59 | 60 | } 61 | 62 | /** 63 | * @uses \Ladoc\Action\SectionQueryAction 64 | * @uses \Ladoc\Index\IndexList 65 | * @uses \Ladoc\Index\ItemList 66 | */ 67 | public function test_it_can_display_search_article(): void 68 | { 69 | $commandTester = $this->getCommandTester(); 70 | 71 | $commandTester->execute([ 72 | 'section' => 'artisan', 73 | 'query' => ['repl'], 74 | ]); 75 | 76 | $commandTester->assertCommandIsSuccessful(); 77 | $output = $commandTester->getDisplay(); 78 | 79 | $this->assertStringContainsString('Tinker (REPL)', $output); 80 | } 81 | 82 | private function getCommandTester(): CommandTester 83 | { 84 | $application = new Application(); 85 | $application->add(new MainCommand( 86 | 'test-version', 87 | ROOT_TEST.'/data', 88 | true 89 | )); 90 | 91 | $application->setAutoExit(false); 92 | 93 | return new CommandTester($application->find('ladoc')); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /tests/Unit/InputResolverTest.php: -------------------------------------------------------------------------------- 1 | createMock(IndexManager::class); 23 | 24 | $inputResolver = new InputResolver($indexManager); 25 | 26 | $action = $inputResolver->resolve('list'); 27 | 28 | $this->assertInstanceOf(Action\ListAction::class, $action); 29 | } 30 | 31 | 32 | /** 33 | * @uses \Ladoc\Action\ListAction 34 | */ 35 | public function test_it_can_get_main_list_letter_filter(): void 36 | { 37 | $indexManager = $this->createMock(IndexManager::class); 38 | 39 | $inputResolver = new InputResolver($indexManager); 40 | 41 | $action = $inputResolver->resolve('list', ['letter' => 'a']); 42 | 43 | $this->assertInstanceOf(Action\ListAction::class, $action); 44 | } 45 | 46 | /** 47 | * @uses \Ladoc\Action\SectionListAction 48 | * @uses \Ladoc\Index\IndexList 49 | * @uses \Ladoc\Index\ItemList 50 | */ 51 | public function test_it_can_get_section_by_index(): void 52 | { 53 | $indexManager = $this->createMock(IndexManager::class); 54 | 55 | $mainIndex = new IndexList('Main List'); 56 | $mainIndex->attach(new ItemList('Artisan', 'artisan', new IndexList())); 57 | 58 | $indexManager 59 | ->method('getMainIndex') 60 | ->willReturn($mainIndex); 61 | 62 | $inputResolver = new InputResolver($indexManager); 63 | 64 | $action = $inputResolver->resolve(0); 65 | 66 | $this->assertInstanceOf(Action\SectionListAction::class, $action); 67 | } 68 | 69 | /** 70 | * @uses \Ladoc\Action\SectionListAction 71 | */ 72 | public function test_it_can_get_section_by_name(): void 73 | { 74 | $indexManager = $this->createMock(IndexManager::class); 75 | 76 | $inputResolver = new InputResolver($indexManager); 77 | 78 | $action = $inputResolver->resolve('artisan'); 79 | 80 | $this->assertInstanceOf(Action\SectionListAction::class, $action); 81 | } 82 | 83 | /** 84 | * @uses \Ladoc\Action\SectionQueryAction 85 | */ 86 | public function test_it_can_search_section(): void 87 | { 88 | $indexManager = $this->createMock(IndexManager::class); 89 | 90 | $inputResolver = new InputResolver($indexManager); 91 | 92 | $action = $inputResolver->resolve('validation', ['routes']); 93 | 94 | $this->assertInstanceOf(Action\SectionQueryAction::class, $action); 95 | } 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/Index/IndexList.php: -------------------------------------------------------------------------------- 1 | items[] = $itemList; 24 | return $this; 25 | } 26 | 27 | public function add(ItemList $itemList): self 28 | { 29 | $this->items[] = $itemList; 30 | return $this; 31 | } 32 | 33 | public function setName(string $name): self 34 | { 35 | $this->name = $name; 36 | return $this; 37 | } 38 | 39 | public function getName(): ?string 40 | { 41 | return $this->name; 42 | } 43 | 44 | public function count(): int 45 | { 46 | return count($this->items); 47 | } 48 | 49 | public function isEmpty(): bool 50 | { 51 | return $this->count() === 0; 52 | } 53 | 54 | public function get(int $index): ItemList 55 | { 56 | if (isset($this->items[$index]) === false) { 57 | throw new OutOfBoundsException( 58 | sprintf('Index %d does not exist for this section', $index) 59 | ); 60 | } 61 | 62 | return $this->items[$index]; 63 | } 64 | 65 | /** 66 | * @return ItemList[] 67 | */ 68 | public function all(): array 69 | { 70 | return $this->items; 71 | } 72 | 73 | /** 74 | * @return array> 75 | */ 76 | public function toArray(): array 77 | { 78 | return array_map(fn ($item) => $item->toArray(), $this->items); 79 | } 80 | 81 | public function filterByLetter(string $letter): self 82 | { 83 | $indexList = new IndexList( 84 | sprintf('%s | filter: %s', $this->name, strtoupper($letter)) 85 | ); 86 | 87 | foreach ($this->items as $item) { 88 | if (strtolower($item->anchor[0]) == $letter) { 89 | $indexList->add($item); 90 | } 91 | } 92 | 93 | return $indexList; 94 | } 95 | 96 | 97 | /** 98 | * @param array $query 99 | * @return ItemList 100 | */ 101 | public function getNestedItems(array $query): ItemList 102 | { 103 | $firstElement = $this->get($query[0]); 104 | 105 | if ($firstElement->hasChildren() === false) { 106 | return $firstElement; 107 | } 108 | 109 | $next = array_slice($query, 1); 110 | 111 | if (empty($next) || is_null($firstElement->children)) { 112 | return $firstElement; 113 | } 114 | 115 | return $firstElement->children->getNestedItems(array_slice($query, 1)); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /tests/Unit/SplitterTest.php: -------------------------------------------------------------------------------- 1 | 23 |

24 |

Test-1

25 |

lorem

26 |

27 |

Test-2

28 |

lorem

29 | 30 | HTML; 31 | 32 | $splitter = new Splitter($htmlContent); 33 | 34 | $sections = $splitter->splitArticles(new TermwindFormatter()); 35 | 36 | $this->assertCount(2, $sections); 37 | $this->assertEquals('test-1', array_key_first($sections)); 38 | $this->assertEquals( 39 | 'Test-1

lorem

', 40 | str_replace([PHP_EOL, ' '], '', $sections['test-1']) 41 | ); 42 | } 43 | 44 | public function test_it_can_get_first_h1_title(): void 45 | { 46 | $htmlContent = <<<'HTML' 47 |

Test-1

48 |

lorem

49 |

Test-2

50 |

lorem

51 | HTML; 52 | 53 | $splitter = new Splitter($htmlContent); 54 | 55 | $title = $splitter->getTitle(); 56 | $this->assertEquals('Test-1', $title); 57 | } 58 | 59 | public function test_it_return_null_if_html_have_not_h1_title(): void 60 | { 61 | $htmlContent = <<<'HTML' 62 |

Test-2

63 |

lorem

64 | HTML; 65 | 66 | $splitter = new Splitter($htmlContent); 67 | 68 | $title = $splitter->getTitle(); 69 | $this->assertNull($title); 70 | 71 | } 72 | 73 | 74 | /** 75 | * @uses \Ladoc\Index\IndexList 76 | * @uses \Ladoc\Index\ItemList 77 | */ 78 | public function test_it_parse_html_list_to_index_list(): void 79 | { 80 | $htmlContent = <<<'HTML' 81 | 82 |

Test-1

83 |

lorem

84 | 94 |

Test-2

95 |

lorem

96 | HTML; 97 | 98 | $splitter = new Splitter($htmlContent); 99 | 100 | $index = $splitter->getIndexList(); 101 | 102 | $this->assertInstanceOf(IndexList::class, $index); 103 | $this->assertCount(2, $index); 104 | $this->assertEquals('Test-2', $index->get(1)->title); 105 | $this->assertInstanceOf(IndexList::class, $index->get(0)->children); 106 | $this->assertCount(2, $index->get(0)->children); 107 | $this->assertEquals('Test-1.1', $index->get(0)->children->get(0)->title); 108 | 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Documentation for `Console` 2 | 3 |

4 | Ladoc example 5 |

6 | GitHub Workflow Status (master) 7 | Total Downloads 8 | Latest Version 9 | License 10 |

11 |

12 | 13 | ------ 14 | 15 | **Ladoc** allows you to search and browse Laravel documentation in all its versions. 16 | 17 | ## Installation 18 | 19 | ### Using Composer 20 | **Requires [PHP 8.2](https://php.net/releases/)** 21 | 22 | ```bash 23 | composer global require "millancore/ladoc" 24 | ``` 25 | 26 | ---- 27 | 28 | ### or Using Docker 29 | ```bash 30 | docker run -td --name ladoc millancore/ladoc 31 | ``` 32 | 33 | Uses: 34 | ```bash 35 | docker exec -it ladoc sh # (and then zz or ladoc) 36 | ``` 37 | 38 | ## Usage 39 | 40 | > **Tip:** To make it easier to use, create an alias, I usually use `zz`. 41 | 42 | ### Search 43 | 44 | `ladoc
` 45 | 46 | ```bash 47 | ladoc blade @once 48 | ``` 49 | ### List all sections 50 | 51 | simply execute the command without parameters, you will see a list of all the sections (in brackets). 52 | 53 | ```bash 54 | ladoc 55 | ``` 56 | Result: 57 | ``` 58 | Main List 59 | 60 | • [0] Artisan Console (artisan) 61 | • [1] Authentication (authentication) 62 | • [2] Authorization (authorization) 63 | • [3] Laravel Cashier (Stripe) (billing) 64 | • [4] Blade Templates (blade) 65 | ... 66 | ``` 67 | ### Filter Main List 68 | To simplify the navigation you can filter main list with '--letter' or `-l` and initial letter. 69 | 70 | ```bash 71 | ladoc -lv 72 | ``` 73 | Result: 74 | ``` 75 | Main List | filter: V 76 | 77 | • [0] Validation (validation) 78 | • [1] Views (views) 79 | ``` 80 | 81 | ### Navigation System 82 | You can navigate through all sections using the indexes in the list. 83 | 84 | ```bash 85 | ladoc 4 86 | ``` 87 | Result: 88 | ``` 89 | Blade Templates 90 | 91 | • [0] Introduction (+) 92 | • [1] Displaying Data (+) 93 | • [2] Blade Directives (+) 94 | ... 95 | ``` 96 | and continue in that way 97 | 98 | ```bash 99 | ladoc 4 2 100 | ``` 101 | Result: 102 | ``` 103 | Blade Directives 104 | 105 | In addition to template inheritance and displaying data... 106 | 107 | ──────────────────────── 108 | • [0] If Statements 109 | • [1] Switch Statements 110 | • [2] Loops 111 | • [3] The Loop Variable 112 | ... 113 | ``` 114 | ### Using the search with index 115 | 116 | You can search directly in a section using its index. `ladoc 4 @once` it's equal to `ladoc blade @once`. 117 | 118 | ### Versions 119 | 120 | Ladoc allows you to search all versions of Laravel, just use `--branch` or `-b` to define the version you want to use. 121 | 122 | ```bash 123 | ladoc -b5.2 blade 124 | ``` 125 | > If no version is set, use the latest one. 126 | 127 | --- 128 | 129 | Ladoc is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**. 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /tests/Unit/Index/IndexListTest.php: -------------------------------------------------------------------------------- 1 | attach(new ItemList('title', 'anchor', new IndexList())); 19 | 20 | $this->assertEquals(1, $indexList->count()); 21 | } 22 | 23 | public function test_it_can_set_name(): void 24 | { 25 | $indexList = new IndexList(); 26 | $indexList->setName('name'); 27 | 28 | $this->assertSame('name', $indexList->getName()); 29 | } 30 | 31 | public function test_it_can_get_by_index(): void 32 | { 33 | $indexList = new IndexList(); 34 | $indexList->attach(new ItemList('first title', 'first anchor')); 35 | $indexList->attach(new ItemList('second title', 'second anchor')); 36 | 37 | $this->assertSame('first title', $indexList->get(0)->title); 38 | } 39 | 40 | public function test_it_can_get_all_items(): void 41 | { 42 | $indexList = new IndexList(); 43 | $indexList->attach(new ItemList('title', 'anchor')); 44 | $indexList->attach(new ItemList('title', 'anchor')); 45 | $indexList->attach(new ItemList('title', 'anchor')); 46 | 47 | $this->assertCount(3, $indexList->all()); 48 | } 49 | 50 | public function test_it_can_validate_if_empty(): void 51 | { 52 | $indexList = new IndexList(); 53 | $this->assertTrue($indexList->isEmpty()); 54 | } 55 | 56 | public function test_it_can_filter_by_first_letter(): void 57 | { 58 | $indexList = new IndexList(); 59 | $indexList->attach(new ItemList('title', 'anchor', new IndexList())); 60 | $indexList->attach(new ItemList('title', 'anchor', new IndexList())); 61 | $indexList->attach(new ItemList('title', 'anchor', new IndexList())); 62 | 63 | $this->assertCount(3, $indexList->all()); 64 | $this->assertCount(0, $indexList->filterByLetter('t')); 65 | $this->assertCount(3, $indexList->filterByLetter('a')); 66 | } 67 | 68 | public function test_it_can_get_nested_item_as_array(): void 69 | { 70 | $indexList = new IndexList(); 71 | $indexList->attach(new ItemList('child title', 'anchor', new IndexList())); 72 | 73 | $this->assertSame([ 74 | [ 75 | 'title' => 'child title', 76 | 'anchor' => 'anchor', 77 | 'child' => [] 78 | ] 79 | ], $indexList->toArray()); 80 | } 81 | 82 | public function test_it_can_get_nested_items(): void 83 | { 84 | $firstLevel = new IndexList(); 85 | $secondLevel = new IndexList(); 86 | $thirdLevel = new IndexList(); 87 | 88 | $thirdLevel->attach(new ItemList('third level', 'anchor')); 89 | $secondLevel->attach(new ItemList('first child second level', 'anchor')); 90 | $secondLevel->attach(new ItemList('second child second level', 'anchor', $thirdLevel)); 91 | $firstLevel->attach(new ItemList('first level', 'anchor', $secondLevel)); 92 | 93 | 94 | $this->assertSame([ 95 | 'title' => 'third level', 96 | 'anchor' => 'anchor', 97 | 'child' => null 98 | ], $firstLevel->getNestedItems([0, 1, 0])->toArray()); 99 | 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /tests/Unit/Index/IndexManagerTest.php: -------------------------------------------------------------------------------- 1 | fileManager = new FileManager( 31 | Version::V10, 32 | ROOT_TEST . '/data/.docs', 33 | ROOT_TEST . '/data/index' 34 | ); 35 | 36 | $this->indexManager = new IndexManager($this->fileManager); 37 | parent::setUp(); 38 | } 39 | 40 | public function test_it_can_create_index(): void 41 | { 42 | $this->indexManager->createIndex(); 43 | $indexPath = $this->fileManager->getIndexPath(); 44 | 45 | $this->assertFileExists($indexPath); 46 | $this->assertFileExists($indexPath . '/index.ladoc'); 47 | $this->assertFileExists($indexPath . '/artisan/index.ladoc'); 48 | $this->assertFileExists($indexPath . '/validation/index.ladoc'); 49 | } 50 | 51 | 52 | public function test_it_check_if_index_directory_exist(): void 53 | { 54 | $this->fileManager->removeIndexDirectory(); 55 | 56 | $this->assertFalse($this->indexManager->check()); 57 | 58 | $this->indexManager->createIndex(); 59 | $this->assertTrue($this->indexManager->check()); 60 | } 61 | 62 | public function test_it_can_return_section_path(): void 63 | { 64 | $this->refreshIndex(); 65 | 66 | $this->assertEquals( 67 | ROOT_TEST . '/data/index/10.x/artisan', 68 | $this->indexManager->getSectionPath('artisan') 69 | ); 70 | } 71 | 72 | public function test_it_can_get_main_index(): void 73 | { 74 | $this->refreshIndex(); 75 | 76 | $mainList = $this->indexManager->getMainIndex(); 77 | 78 | $this->assertInstanceOf(IndexList::class, $mainList); 79 | $this->assertEquals('Main List', $mainList->getName()); 80 | $this->assertEquals('Artisan Console', $mainList->get(0)->title); 81 | $this->assertEquals('Validation', $mainList->get(1)->title); 82 | 83 | } 84 | 85 | public function test_it_can_get_section_index(): void 86 | { 87 | $this->refreshIndex(); 88 | 89 | $sectionList = $this->indexManager->getSectionIndex('artisan'); 90 | 91 | $this->assertInstanceOf(IndexList::class, $sectionList); 92 | $this->assertEquals('Artisan Console', $sectionList->getName()); 93 | $this->assertEquals('Introduction', $sectionList->get(0)->title); 94 | $this->assertEquals('Writing Commands', $sectionList->get(1)->title); 95 | ; 96 | } 97 | 98 | public function test_it_can_get_section_article(): void 99 | { 100 | $this->refreshIndex(); 101 | 102 | $htmlArticleFile = $this->indexManager->getArticle('artisan', 'writing-commands'); 103 | 104 | $this->assertStringContainsString('

Writing Commands

', $htmlArticleFile); 105 | } 106 | 107 | 108 | 109 | private function refreshIndex(): void 110 | { 111 | $this->fileManager->removeIndexDirectory(); 112 | $this->indexManager->createIndex(); 113 | } 114 | 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/Command/MainCommand.php: -------------------------------------------------------------------------------- 1 | addArgument( 39 | 'section', 40 | InputArgument::OPTIONAL, 41 | 'Section name', 42 | 'list' 43 | ); 44 | 45 | $this->addArgument( 46 | 'query', 47 | InputArgument::IS_ARRAY, 48 | 'Search string' 49 | ); 50 | 51 | $this->addOption( 52 | 'branch', 53 | 'b', 54 | InputArgument::OPTIONAL, 55 | 'Laravel version branch', 56 | Version::getLatestVersion()->value 57 | ); 58 | 59 | $this->addOption( 60 | 'letter', 61 | 'l', 62 | InputArgument::OPTIONAL, 63 | 'Filter Main list by letter', 64 | null 65 | ); 66 | } 67 | 68 | /** 69 | * @throws \Exception 70 | * @throws CommonMarkException 71 | */ 72 | protected function execute(InputInterface $input, OutputInterface $output): int 73 | { 74 | $section = $input->getArgument('section'); 75 | $query = $input->getArgument('query'); 76 | $versionInput = $input->getOption('branch'); 77 | 78 | $version = Version::fromValue($versionInput); 79 | 80 | if ($version !== Version::getLatestVersion()) { 81 | $output->writeln( 82 | sprintf('Using old version: %s', $version->value) 83 | ); 84 | } 85 | 86 | $fileManager = new FileManager( 87 | $version, 88 | $this->rootPath . '/.docs', 89 | $this->rootPath . '/index' 90 | ); 91 | 92 | $indexManager = new IndexManager($fileManager); 93 | 94 | if (!$indexManager->check()) { 95 | 96 | $output->writeln(sprintf('Download v%s and Indexing...', $version->value)); 97 | 98 | (new Repository( 99 | $fileManager, 100 | new ProcessFactory(), 101 | ))->check(); 102 | $indexManager->createIndex(); 103 | } 104 | 105 | $inputResolver = new InputResolver($indexManager); 106 | $action = $inputResolver->resolve($section, $query, $input->getOptions()); 107 | 108 | $content = $action->execute( 109 | $query, 110 | $input->getOptions() 111 | ); 112 | 113 | if ($this->isTestMode) { 114 | $output->write($content); 115 | return Command::SUCCESS; 116 | } 117 | 118 | // @codeCoverageIgnoreStart 119 | (new Termwind( 120 | new Styles(require $this->rootPath . '/styles.php') 121 | ))->render($content); 122 | 123 | return Command::SUCCESS; 124 | // @codeCoverageIgnoreEnd 125 | } 126 | 127 | 128 | } 129 | -------------------------------------------------------------------------------- /tests/Unit/FileManagerTest.php: -------------------------------------------------------------------------------- 1 | newFileManager(); 18 | 19 | $this->assertEquals(ROOT_TEST.'/data/index/10.x', $fileManager->getIndexPath()); 20 | } 21 | 22 | public function test_get_doc_path(): void 23 | { 24 | $fileManager = $this->newFileManager(); 25 | 26 | $this->assertEquals(ROOT_TEST.'/data/.docs/10.x', $fileManager->getDocPath()); 27 | } 28 | 29 | public function test_get_version(): void 30 | { 31 | $fileManager = $this->newFileManager(); 32 | 33 | $this->assertEquals(Version::V10, $fileManager->getVersion()); 34 | } 35 | 36 | public function test_get_file_content(): void 37 | { 38 | $fileManager = $this->newFileManager(); 39 | 40 | $fileManager->saveIndexFile('section/test.html', 'test'); 41 | 42 | $content = $fileManager->getFileContent('section/test.html'); 43 | 44 | $this->assertIsString($content); 45 | } 46 | 47 | public function test_try_to_get_invalid_file_content(): void 48 | { 49 | $fileManager = $this->newFileManager(); 50 | 51 | $this->expectException(\Ladoc\Exception\FileManagerException::class); 52 | 53 | $fileManager->getFileContent('no-section/test.invalid'); 54 | } 55 | 56 | public function test_get_files_from_repo_directory(): void 57 | { 58 | $fileManager = $this->newFileManager(); 59 | 60 | $files = $fileManager->getRepositoryFiles(); 61 | 62 | $this->assertIsArray($files); 63 | $this->assertCount(2, $files); 64 | $this->assertEquals([ 65 | ROOT_TEST.'/data/.docs/10.x/artisan.md', 66 | ROOT_TEST.'/data/.docs/10.x/validation.md' 67 | ], array_values($files)); 68 | } 69 | 70 | public function test_get_files_from_no_exist_directory(): void 71 | { 72 | $fileManager = new FileManager( 73 | Version::V10, 74 | 'wrong/path', 75 | 'wrong/path' 76 | ); 77 | 78 | $this->expectException(FileManagerException::class); 79 | $this->expectExceptionMessage('Repository folder wrong/path/10.x not found'); 80 | $fileManager->getRepositoryFiles(); 81 | } 82 | 83 | public function test_it_can_save_file(): void 84 | { 85 | $fileManager = $this->newFileManager(); 86 | 87 | $fileManager->saveIndexFile('section/test.html', 'test'); 88 | 89 | $this->assertFileExists(ROOT_TEST . '/data/index/10.x/section/test.html'); 90 | $this->assertEquals('test', file_get_contents(ROOT_TEST . '/data/index/10.x/section/test.html')); 91 | } 92 | 93 | public function test_it_can_remove_index_directory(): void 94 | { 95 | $fileManager = $this->newFileManager(); 96 | 97 | $fileManager->removeIndexDirectory(); 98 | $this->assertDirectoryDoesNotExist(ROOT_TEST . '/data/index/10.x'); 99 | } 100 | 101 | public function test_it_try_two_remove_twice_index_directory(): void 102 | { 103 | $fileManager = $this->newFileManager(); 104 | 105 | $fileManager->removeIndexDirectory(); 106 | $fileManager->removeIndexDirectory(); 107 | $this->assertDirectoryDoesNotExist(ROOT_TEST . '/data/index/10.x'); 108 | } 109 | 110 | private function newFileManager(): FileManager 111 | { 112 | return new FileManager( 113 | Version::V10, 114 | ROOT_TEST . '/data/.docs', 115 | ROOT_TEST . '/data/index' 116 | ); 117 | } 118 | 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/Splitter.php: -------------------------------------------------------------------------------- 1 | domDocument = new DOMDocument(); 20 | $this->domDocument->loadHTML($htmlContent, LIBXML_NOERROR | LIBXML_COMPACT); 21 | } 22 | 23 | 24 | /** 25 | * @param FormatterInterface $formatter 26 | * @return array 27 | */ 28 | public function splitArticles(FormatterInterface $formatter): array 29 | { 30 | $htmlContent = $formatter->format($this->htmlContent); 31 | 32 | $domDocument = new DOMDocument(); 33 | $domDocument->loadHTML($htmlContent, LIBXML_NOERROR | LIBXML_COMPACT); 34 | 35 | $xpath = new DOMXPath($domDocument); 36 | 37 | $elements = $xpath->query('//p[a/@name]'); 38 | 39 | if (!$elements) { 40 | return []; 41 | } 42 | 43 | $articles = []; 44 | $currentKey = ''; 45 | $currentSection = ''; 46 | 47 | /** @var DOMElement $element */ 48 | foreach ($elements as $element) { 49 | 50 | /** @var DOMElement $anchorElement */ 51 | $anchorElement = $element->getElementsByTagName('a')->item(0); 52 | $name = $anchorElement->getAttribute('name'); 53 | 54 | if (!empty($currentSection)) { 55 | $articles[$currentKey] = $currentSection; 56 | } 57 | 58 | $currentKey = $name; 59 | $currentSection = ''; 60 | 61 | $currentNode = $element; 62 | while ($currentNode = $currentNode->nextSibling) { 63 | if ($currentNode instanceof DOMElement 64 | && $currentNode->tagName === 'p' 65 | && $currentNode->childNodes->length === 1 66 | && $currentNode->childNodes[0] instanceof DOMElement 67 | && $currentNode->childNodes[0]->tagName === 'a') { 68 | break; 69 | } 70 | 71 | $currentSection .= $domDocument->saveHTML($currentNode); 72 | } 73 | } 74 | 75 | if (!empty($currentSection)) { 76 | $articles[$currentKey] = $currentSection; 77 | } 78 | 79 | return array_filter($articles); 80 | } 81 | 82 | public function getTitle(): ?string 83 | { 84 | $firstTitle = $this->domDocument->getElementsByTagName('h1')[0]; 85 | 86 | if (!$firstTitle) { 87 | return null; 88 | } 89 | 90 | return $firstTitle->nodeValue; 91 | } 92 | 93 | 94 | public function getIndexList(): IndexList 95 | { 96 | // Get first list element 97 | $list = $this->domDocument->getElementsByTagName('ul')[0]; 98 | 99 | $sectionList = $this->parseList($list); 100 | 101 | if ($this->getTitle()) { 102 | $sectionList->setName($this->getTitle()); 103 | } 104 | 105 | return $sectionList; 106 | } 107 | 108 | public function parseList(?DOMElement $list): IndexList 109 | { 110 | $result = new IndexList(); 111 | 112 | if (!$list) { 113 | return $result; 114 | } 115 | 116 | /** @var DOMElement $item */ 117 | foreach ($list->childNodes as $item) { 118 | if ($item->nodeName === 'li') { 119 | 120 | if(empty($item->nodeValue)) { 121 | continue; 122 | } 123 | 124 | $children = $item->getElementsByTagName('ul'); 125 | $anchor = $item->getElementsByTagName('a'); 126 | 127 | $key = str_replace('#', '', $anchor[0]->getAttribute('href')); 128 | 129 | $value = $anchor[0]->nodeValue; 130 | 131 | $result->attach(new ItemList($value, $key, $this->parseList($children[0]))); 132 | } 133 | } 134 | 135 | return $result; 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /tests/data/artisan.ladoc: -------------------------------------------------------------------------------- 1 | O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:7:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:12:"Introduction";s:6:"anchor";s:12:"introduction";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:1:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:13:"Tinker (REPL)";s:6:"anchor";s:6:"tinker";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";N;}}i:1;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:16:"Writing Commands";s:6:"anchor";s:16:"writing-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:3:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:19:"Generating Commands";s:6:"anchor";s:19:"generating-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:1;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:17:"Command Structure";s:6:"anchor";s:17:"command-structure";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:2;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:16:"Closure Commands";s:6:"anchor";s:16:"closure-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";N;}}i:2;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:27:"Defining Input Expectations";s:6:"anchor";s:27:"defining-input-expectations";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:4:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:9:"Arguments";s:6:"anchor";s:9:"arguments";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:1;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:7:"Options";s:6:"anchor";s:7:"options";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:2;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:12:"Input Arrays";s:6:"anchor";s:12:"input-arrays";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:3;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:18:"Input Descriptions";s:6:"anchor";s:18:"input-descriptions";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";N;}}i:3;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:11:"Command I/O";s:6:"anchor";s:10:"command-io";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:3:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:16:"Retrieving Input";s:6:"anchor";s:16:"retrieving-input";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:1;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:19:"Prompting For Input";s:6:"anchor";s:19:"prompting-for-input";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:2;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:14:"Writing Output";s:6:"anchor";s:14:"writing-output";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";N;}}i:4;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:20:"Registering Commands";s:6:"anchor";s:20:"registering-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}i:5;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:35:"Programmatically Executing Commands";s:6:"anchor";s:35:"programmatically-executing-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:1:{i:0;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:36:"Calling Commands From Other Commands";s:6:"anchor";s:36:"calling-commands-from-other-commands";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";N;}}i:6;O:20:"Ladoc\Index\ItemList":3:{s:5:"title";s:18:"Stub Customization";s:6:"anchor";s:18:"stub-customization";s:8:"children";O:21:"Ladoc\Index\IndexList":2:{s:28:"Ladoc\Index\IndexListitems";a:0:{}s:27:"Ladoc\Index\IndexListname";N;}}}s:27:"Ladoc\Index\IndexListname";s:15:"Artisan Console";} -------------------------------------------------------------------------------- /src/Index/IndexManager.php: -------------------------------------------------------------------------------- 1 | indexFolderExist() && $this->mainIndexFileExist(); 30 | } 31 | 32 | /** 33 | * @throws FileManagerException 34 | * @throws CommonMarkException 35 | */ 36 | public function createIndex(): void 37 | { 38 | $files = $this->fileManager->getRepositoryFiles(['.git', 'documentation.md']); 39 | 40 | $mainIndex = new IndexList('Main List'); 41 | 42 | foreach ($files as $file) { 43 | $this->createIndexByFile($file, $mainIndex); 44 | } 45 | 46 | $this->saveMainIndex($mainIndex); 47 | } 48 | 49 | /** 50 | * @throws FileManagerException 51 | */ 52 | public function getMainIndex(): IndexList 53 | { 54 | return unserialize($this->fileManager->getFileContent($this->indexFileName)); 55 | } 56 | 57 | /** 58 | * @throws FileManagerException 59 | */ 60 | public function saveMainIndex(IndexList $indexList): void 61 | { 62 | $this->fileManager->saveIndexFile( 63 | $this->indexFileName, 64 | serialize($indexList) 65 | ); 66 | } 67 | 68 | /** 69 | * @throws Exception 70 | */ 71 | public function getSectionIndex(string $section): IndexList 72 | { 73 | if (!$this->sectionIndexFileExist($section)) { 74 | throw new Exception(sprintf('Section %s not found', $section)); 75 | } 76 | 77 | return unserialize($this->fileManager->getFileContent( 78 | $section . '/' . $this->indexFileName 79 | )); 80 | } 81 | 82 | public function getSectionPath(string $section): string 83 | { 84 | return $this->fileManager->getIndexPath() . '/' . $section; 85 | } 86 | 87 | 88 | public function indexFolderExist(): bool 89 | { 90 | return is_dir($this->fileManager->getIndexPath()); 91 | } 92 | 93 | public function mainIndexFileExist(): bool 94 | { 95 | return file_exists($this->fileManager->getIndexPath() . '/' . $this->indexFileName); 96 | } 97 | 98 | 99 | public function sectionIndexFileExist(string $section): bool 100 | { 101 | return file_exists($this->fileManager->getIndexPath() . '/' . $section . '/' . $this->indexFileName); 102 | } 103 | 104 | /** 105 | * @throws FileManagerException 106 | * @throws CommonMarkException 107 | */ 108 | private function createIndexByFile(string $file, IndexList $mainIndex): void 109 | { 110 | $markdownContent = file_get_contents($file); 111 | 112 | if($markdownContent === false) { 113 | throw new FileManagerException(sprintf('File %s is empty', $file)); 114 | } 115 | 116 | $section = pathinfo($file, PATHINFO_FILENAME); 117 | 118 | $html = (new CommonMarkConverter())->convert($markdownContent); 119 | $splitter = new Splitter($html); 120 | 121 | if ($splitter->getTitle()) { 122 | $mainIndex->attach(new ItemList($splitter->getTitle(), $section)); 123 | } 124 | 125 | $section = new Section( 126 | $section, 127 | $splitter->getIndexList(), 128 | $splitter->splitArticles(new TermwindFormatter()) 129 | ); 130 | 131 | $this->saveSection($section); 132 | } 133 | 134 | /** 135 | * @throws FileManagerException 136 | */ 137 | private function saveSection(Section $section): void 138 | { 139 | foreach ($section->articles as $name => $content) { 140 | 141 | $filename = strtolower($name) . '.html'; 142 | 143 | $this->fileManager->saveIndexFile( 144 | $section->name . '/' . $filename, 145 | $content 146 | ); 147 | } 148 | 149 | if (!$section->indexList->isEmpty()) { 150 | $this->fileManager->saveIndexFile($section->name. '/' . $this->indexFileName, serialize($section->indexList)); 151 | } 152 | } 153 | 154 | /** 155 | * @throws FileManagerException 156 | */ 157 | public function getArticle(string $section, string $anchor): string 158 | { 159 | return $this->fileManager->getFileContent($section . '/' . $anchor . '.html'); 160 | } 161 | 162 | } 163 | -------------------------------------------------------------------------------- /src/FileManager.php: -------------------------------------------------------------------------------- 1 | docsPath . '/' . $this->version->value; 26 | } 27 | 28 | public function getIndexPath(): string 29 | { 30 | return $this->indexPath . '/' . $this->version->value; 31 | } 32 | 33 | public function getVersion(): Version 34 | { 35 | return $this->version; 36 | } 37 | 38 | /** 39 | * @param array $exclude 40 | * @return string[] 41 | * @throws FileManagerException 42 | */ 43 | public function getRepositoryFiles(array $exclude = []): array 44 | { 45 | $path = $this->getDocPath(); 46 | 47 | if (!is_dir($path)) { 48 | throw new FileManagerException(sprintf('Repository folder %s not found', $path)); 49 | } 50 | 51 | return $this->getFolderFiles($path, $exclude); 52 | } 53 | 54 | 55 | /** 56 | * @param string $path 57 | * @param array $exclude 58 | * @return array 59 | */ 60 | private function getFolderFiles(string $path, array $exclude = []): array 61 | { 62 | $excludeFiles = ['.', '..']; 63 | $arrayFiles = scandir($path); 64 | 65 | if ($arrayFiles === false) { 66 | return []; 67 | } 68 | 69 | $exclude = array_merge($exclude, $excludeFiles); 70 | $files = array_filter($arrayFiles, fn ($file) => !in_array($file, $exclude)); 71 | 72 | return array_map(fn ($file) => $path . '/' . $file, $files); 73 | } 74 | 75 | /** 76 | * @param string $filename 77 | * @param string $content 78 | * @return void 79 | * @throws FileManagerException 80 | */ 81 | private function save(string $filename, string $content): void 82 | { 83 | $successCreateDir = $this->createDirectory(dirname($filename)); 84 | 85 | if (!$successCreateDir) { 86 | throw new FileManagerException('Error to create directory'); 87 | 88 | } 89 | 90 | file_put_contents($filename, $content); 91 | } 92 | 93 | 94 | /** 95 | * @return void 96 | */ 97 | public function removeIndexDirectory(): void 98 | { 99 | if (!is_dir($this->getIndexPath())) { 100 | return; 101 | } 102 | 103 | $this->removeDirectory($this->getIndexPath()); 104 | } 105 | 106 | public function removeDocDirectory(): void 107 | { 108 | if (!is_dir($this->getDocPath())) { 109 | return; 110 | } 111 | 112 | $this->removeDirectory($this->getDocPath()); 113 | } 114 | 115 | /** 116 | * @param string $filename 117 | * @return string 118 | * @throws FileManagerException 119 | */ 120 | public function getFileContent(string $filename): string 121 | { 122 | $path = $this->getIndexPath() . '/' . $filename; 123 | 124 | if (!file_exists($path)) { 125 | throw new FileManagerException(sprintf('File %s not found', $path)); 126 | } 127 | 128 | $content = file_get_contents($path); 129 | 130 | if ($content === false) { 131 | throw new FileManagerException(sprintf('Error to read file %s', $path)); 132 | } 133 | 134 | return $content; 135 | } 136 | 137 | 138 | /** 139 | * @param string $filename 140 | * @param string $content 141 | * @return void 142 | * @throws FileManagerException 143 | */ 144 | public function saveIndexFile(string $filename, string $content): void 145 | { 146 | $path = $this->getIndexPath() . '/' . $filename; 147 | $this->save($path, $content); 148 | } 149 | 150 | 151 | /** 152 | * @param string $path 153 | * @return void 154 | */ 155 | private function removeDirectory(string $path): void 156 | { 157 | $directoryIterator = new RecursiveDirectoryIterator( 158 | $path, 159 | FilesystemIterator::SKIP_DOTS 160 | ); 161 | 162 | $iterator = new RecursiveIteratorIterator( 163 | $directoryIterator, 164 | RecursiveIteratorIterator::CHILD_FIRST 165 | ); 166 | 167 | foreach ($iterator as $file) { 168 | if ($file->isDir()) { 169 | rmdir($file->getPathname()); 170 | } else { 171 | unlink($file->getPathname()); 172 | } 173 | } 174 | 175 | rmdir($path); 176 | } 177 | 178 | /** 179 | * @param string $path 180 | * @return bool 181 | */ 182 | public function createDirectory(string $path): bool 183 | { 184 | if (!is_dir($path)) { 185 | return mkdir($path, 0777, true); 186 | } 187 | 188 | return true; 189 | } 190 | 191 | } 192 | -------------------------------------------------------------------------------- /tests/data/.docs/10.x/artisan.md: -------------------------------------------------------------------------------- 1 | # Artisan Console 2 | 3 | - [Introduction](#introduction) 4 | - [Tinker (REPL)](#tinker) 5 | - [Writing Commands](#writing-commands) 6 | - [Generating Commands](#generating-commands) 7 | - [Command Structure](#command-structure) 8 | - [Closure Commands](#closure-commands) 9 | - [Defining Input Expectations](#defining-input-expectations) 10 | - [Arguments](#arguments) 11 | - [Options](#options) 12 | - [Input Arrays](#input-arrays) 13 | - [Input Descriptions](#input-descriptions) 14 | - [Command I/O](#command-io) 15 | - [Retrieving Input](#retrieving-input) 16 | - [Prompting For Input](#prompting-for-input) 17 | - [Writing Output](#writing-output) 18 | - [Registering Commands](#registering-commands) 19 | - [Programmatically Executing Commands](#programmatically-executing-commands) 20 | - [Calling Commands From Other Commands](#calling-commands-from-other-commands) 21 | - [Stub Customization](#stub-customization) 22 | 23 | 24 | ## Introduction 25 | 26 | Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. To view a list of all available Artisan commands, you may use the `list` command: 27 | 28 | php artisan list 29 | 30 | Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with `help`: 31 | 32 | php artisan help migrate 33 | 34 | 35 | ### Tinker (REPL) 36 | 37 | Laravel Tinker is a powerful REPL for the Laravel framework, powered by the [PsySH](https://github.com/bobthecow/psysh) package. 38 | 39 | #### Installation 40 | 41 | All Laravel applications include Tinker by default. However, you may install it manually if needed using Composer: 42 | 43 | composer require laravel/tinker 44 | 45 | #### Usage 46 | 47 | Tinker allows you to interact with your entire Laravel application on the command line, including the Eloquent ORM, jobs, events, and more. To enter the Tinker environment, run the `tinker` Artisan command: 48 | 49 | php artisan tinker 50 | 51 | You can publish Tinker's configuration file using the `vendor:publish` command: 52 | 53 | php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider" 54 | 55 | > {note} The `dispatch` helper function and `dispatch` method on the `Dispatchable` class depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should use `Bus::dispatch` or `Queue::push` to dispatch jobs. 56 | 57 | #### Command Whitelist 58 | 59 | Tinker utilizes a white-list to determine which Artisan commands are allowed to be run within its shell. By default, you may run the `clear-compiled`, `down`, `env`, `inspire`, `migrate`, `optimize`, and `up` commands. If you would like to white-list more commands you may add them to the `commands` array in your `tinker.php` configuration file: 60 | 61 | 'commands' => [ 62 | // App\Console\Commands\ExampleCommand::class, 63 | ], 64 | 65 | #### Classes That Should Not Be Aliased 66 | 67 | Typically, Tinker automatically aliases classes as you require them in Tinker. However, you may wish to never alias some classes. You may accomplish this by listing the classes in the `dont_alias` array of your `tinker.php` configuration file: 68 | 69 | 'dont_alias' => [ 70 | App\User::class, 71 | ], 72 | 73 | 74 | ## Writing Commands 75 | 76 | In addition to the commands provided with Artisan, you may also build your own custom commands. Commands are typically stored in the `app/Console/Commands` directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer. 77 | 78 | 79 | ### Generating Commands 80 | 81 | To create a new command, use the `make:command` Artisan command. This command will create a new command class in the `app/Console/Commands` directory. Don't worry if this directory does not exist in your application, since it will be created the first time you run the `make:command` Artisan command. The generated command will include the default set of properties and methods that are present on all commands: 82 | 83 | php artisan make:command SendEmails 84 | 85 | 86 | ### Command Structure 87 | 88 | After generating your command, you should fill in the `signature` and `description` properties of the class, which will be used when displaying your command on the `list` screen. The `handle` method will be called when your command is executed. You may place your command logic in this method. 89 | 90 | > {tip} For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example below, note that we inject a service class to do the "heavy lifting" of sending the e-mails. 91 | 92 | Let's take a look at an example command. Note that we are able to inject any dependencies we need into the command's `handle` method. The Laravel [service container](/docs/{{version}}/container) will automatically inject all dependencies that are type-hinted in this method's signature: 93 | 94 | send(User::find($this->argument('user'))); 137 | } 138 | } 139 | 140 | 141 | ### Closure Commands 142 | 143 | Closure based commands provide an alternative to defining console commands as classes. In the same way that route Closures are an alternative to controllers, think of command Closures as an alternative to command classes. Within the `commands` method of your `app/Console/Kernel.php` file, Laravel loads the `routes/console.php` file: 144 | 145 | /** 146 | * Register the Closure based commands for the application. 147 | * 148 | * @return void 149 | */ 150 | protected function commands() 151 | { 152 | require base_path('routes/console.php'); 153 | } 154 | 155 | Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your Closure based routes using the `Artisan::command` method. The `command` method accepts two arguments: the [command signature](#defining-input-expectations) and a Closure which receives the commands arguments and options: 156 | 157 | Artisan::command('build {project}', function ($project) { 158 | $this->info("Building {$project}!"); 159 | }); 160 | 161 | The Closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class. 162 | 163 | #### Type-Hinting Dependencies 164 | 165 | In addition to receiving your command's arguments and options, command Closures may also type-hint additional dependencies that you would like resolved out of the [service container](/docs/{{version}}/container): 166 | 167 | use App\DripEmailer; 168 | use App\User; 169 | 170 | Artisan::command('email:send {user}', function (DripEmailer $drip, $user) { 171 | $drip->send(User::find($user)); 172 | }); 173 | 174 | #### Closure Command Descriptions 175 | 176 | When defining a Closure based command, you may use the `describe` method to add a description to the command. This description will be displayed when you run the `php artisan list` or `php artisan help` commands: 177 | 178 | Artisan::command('build {project}', function ($project) { 179 | $this->info("Building {$project}!"); 180 | })->describe('Build the project'); 181 | 182 | 183 | ## Defining Input Expectations 184 | 185 | When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the `signature` property on your commands. The `signature` property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax. 186 | 187 | 188 | ### Arguments 189 | 190 | All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one **required** argument: `user`: 191 | 192 | /** 193 | * The name and signature of the console command. 194 | * 195 | * @var string 196 | */ 197 | protected $signature = 'email:send {user}'; 198 | 199 | You may also make arguments optional and define default values for arguments: 200 | 201 | // Optional argument... 202 | email:send {user?} 203 | 204 | // Optional argument with default value... 205 | email:send {user=foo} 206 | 207 | 208 | ### Options 209 | 210 | Options, like arguments, are another form of user input. Options are prefixed by two hyphens (`--`) when they are specified on the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option: 211 | 212 | /** 213 | * The name and signature of the console command. 214 | * 215 | * @var string 216 | */ 217 | protected $signature = 'email:send {user} {--queue}'; 218 | 219 | In this example, the `--queue` switch may be specified when calling the Artisan command. If the `--queue` switch is passed, the value of the option will be `true`. Otherwise, the value will be `false`: 220 | 221 | php artisan email:send 1 --queue 222 | 223 | 224 | #### Options With Values 225 | 226 | Next, let's take a look at an option that expects a value. If the user must specify a value for an option, suffix the option name with a `=` sign: 227 | 228 | /** 229 | * The name and signature of the console command. 230 | * 231 | * @var string 232 | */ 233 | protected $signature = 'email:send {user} {--queue=}'; 234 | 235 | In this example, the user may pass a value for the option like so: 236 | 237 | php artisan email:send 1 --queue=default 238 | 239 | You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used: 240 | 241 | email:send {user} {--queue=default} 242 | 243 | 244 | #### Option Shortcuts 245 | 246 | To assign a shortcut when defining an option, you may specify it before the option name and use a | delimiter to separate the shortcut from the full option name: 247 | 248 | email:send {user} {--Q|queue} 249 | 250 | 251 | ### Input Arrays 252 | 253 | If you would like to define arguments or options to expect array inputs, you may use the `*` character. First, let's take a look at an example that specifies an array argument: 254 | 255 | email:send {user*} 256 | 257 | When calling this method, the `user` arguments may be passed in order to the command line. For example, the following command will set the value of `user` to `['foo', 'bar']`: 258 | 259 | php artisan email:send foo bar 260 | 261 | When defining an option that expects an array input, each option value passed to the command should be prefixed with the option name: 262 | 263 | email:send {user} {--id=*} 264 | 265 | php artisan email:send --id=1 --id=2 266 | 267 | 268 | ### Input Descriptions 269 | 270 | You may assign descriptions to input arguments and options by separating the parameter from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines: 271 | 272 | /** 273 | * The name and signature of the console command. 274 | * 275 | * @var string 276 | */ 277 | protected $signature = 'email:send 278 | {user : The ID of the user} 279 | {--queue= : Whether the job should be queued}'; 280 | 281 | 282 | ## Command I/O 283 | 284 | 285 | ### Retrieving Input 286 | 287 | While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the `argument` and `option` methods: 288 | 289 | /** 290 | * Execute the console command. 291 | * 292 | * @return mixed 293 | */ 294 | public function handle() 295 | { 296 | $userId = $this->argument('user'); 297 | 298 | // 299 | } 300 | 301 | If you need to retrieve all of the arguments as an `array`, call the `arguments` method: 302 | 303 | $arguments = $this->arguments(); 304 | 305 | Options may be retrieved just as easily as arguments using the `option` method. To retrieve all of the options as an array, call the `options` method: 306 | 307 | // Retrieve a specific option... 308 | $queueName = $this->option('queue'); 309 | 310 | // Retrieve all options... 311 | $options = $this->options(); 312 | 313 | If the argument or option does not exist, `null` will be returned. 314 | 315 | 316 | ### Prompting For Input 317 | 318 | In addition to displaying output, you may also ask the user to provide input during the execution of your command. The `ask` method will prompt the user with the given question, accept their input, and then return the user's input back to your command: 319 | 320 | /** 321 | * Execute the console command. 322 | * 323 | * @return mixed 324 | */ 325 | public function handle() 326 | { 327 | $name = $this->ask('What is your name?'); 328 | } 329 | 330 | The `secret` method is similar to `ask`, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as a password: 331 | 332 | $password = $this->secret('What is the password?'); 333 | 334 | #### Asking For Confirmation 335 | 336 | If you need to ask the user for a simple confirmation, you may use the `confirm` method. By default, this method will return `false`. However, if the user enters `y` or `yes` in response to the prompt, the method will return `true`. 337 | 338 | if ($this->confirm('Do you wish to continue?')) { 339 | // 340 | } 341 | 342 | #### Auto-Completion 343 | 344 | The `anticipate` method can be used to provide auto-completion for possible choices. The user can still choose any answer, regardless of the auto-completion hints: 345 | 346 | $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); 347 | 348 | Alternatively, you may pass a Closure as the second argument to the `anticipate` method. The Closure will be called each time the user types an input character. The Closure should accept a string parameter containing the user's input so far, and return an array of options for auto-completion: 349 | 350 | $name = $this->anticipate('What is your name?', function ($input) { 351 | // Return auto-completion options... 352 | }); 353 | 354 | #### Multiple Choice Questions 355 | 356 | If you need to give the user a predefined set of choices, you may use the `choice` method. You may set the array index of the default value to be returned if no option is chosen: 357 | 358 | $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex); 359 | 360 | In addition, the `choice` method accepts optional fourth and fifth arguments for determining the maximum number of attempts to select a valid response and whether multiple selections are permitted: 361 | 362 | $name = $this->choice( 363 | 'What is your name?', 364 | ['Taylor', 'Dayle'], 365 | $defaultIndex, 366 | $maxAttempts = null, 367 | $allowMultipleSelections = false 368 | ); 369 | 370 | 371 | ### Writing Output 372 | 373 | To send output to the console, use the `line`, `info`, `comment`, `question` and `error` methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the `info` method will display in the console as green text: 374 | 375 | /** 376 | * Execute the console command. 377 | * 378 | * @return mixed 379 | */ 380 | public function handle() 381 | { 382 | $this->info('Display this on the screen'); 383 | } 384 | 385 | To display an error message, use the `error` method. Error message text is typically displayed in red: 386 | 387 | $this->error('Something went wrong!'); 388 | 389 | If you would like to display plain, uncolored console output, use the `line` method: 390 | 391 | $this->line('Display this on the screen'); 392 | 393 | #### Table Layouts 394 | 395 | The `table` method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data: 396 | 397 | $headers = ['Name', 'Email']; 398 | 399 | $users = App\User::all(['name', 'email'])->toArray(); 400 | 401 | $this->table($headers, $users); 402 | 403 | #### Progress Bars 404 | 405 | For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. First, define the total number of steps the process will iterate through. Then, advance the Progress Bar after processing each item: 406 | 407 | $users = App\User::all(); 408 | 409 | $bar = $this->output->createProgressBar(count($users)); 410 | 411 | $bar->start(); 412 | 413 | foreach ($users as $user) { 414 | $this->performTask($user); 415 | 416 | $bar->advance(); 417 | } 418 | 419 | $bar->finish(); 420 | 421 | For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/current/components/console/helpers/progressbar.html). 422 | 423 | 424 | ## Registering Commands 425 | 426 | Because of the `load` method call in your console kernel's `commands` method, all commands within the `app/Console/Commands` directory will automatically be registered with Artisan. In fact, you are free to make additional calls to the `load` method to scan other directories for Artisan commands: 427 | 428 | /** 429 | * Register the commands for the application. 430 | * 431 | * @return void 432 | */ 433 | protected function commands() 434 | { 435 | $this->load(__DIR__.'/Commands'); 436 | $this->load(__DIR__.'/MoreCommands'); 437 | 438 | // ... 439 | } 440 | 441 | You may also manually register commands by adding its class name to the `$commands` property of your `app/Console/Kernel.php` file. When Artisan boots, all the commands listed in this property will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan: 442 | 443 | protected $commands = [ 444 | Commands\SendEmails::class 445 | ]; 446 | 447 | 448 | ## Programmatically Executing Commands 449 | 450 | Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the `call` method on the `Artisan` facade to accomplish this. The `call` method accepts either the command's name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned: 451 | 452 | Route::get('/foo', function () { 453 | $exitCode = Artisan::call('email:send', [ 454 | 'user' => 1, '--queue' => 'default' 455 | ]); 456 | 457 | // 458 | }); 459 | 460 | Alternatively, you may pass the entire Artisan command to the `call` method as a string: 461 | 462 | Artisan::call('email:send 1 --queue=default'); 463 | 464 | Using the `queue` method on the `Artisan` facade, you may even queue Artisan commands so they are processed in the background by your [queue workers](/docs/{{version}}/queues). Before using this method, make sure you have configured your queue and are running a queue listener: 465 | 466 | Route::get('/foo', function () { 467 | Artisan::queue('email:send', [ 468 | 'user' => 1, '--queue' => 'default' 469 | ]); 470 | 471 | // 472 | }); 473 | 474 | You may also specify the connection or queue the Artisan command should be dispatched to: 475 | 476 | Artisan::queue('email:send', [ 477 | 'user' => 1, '--queue' => 'default' 478 | ])->onConnection('redis')->onQueue('commands'); 479 | 480 | #### Passing Array Values 481 | 482 | If your command defines an option that accepts an array, you may pass an array of values to that option: 483 | 484 | Route::get('/foo', function () { 485 | $exitCode = Artisan::call('email:send', [ 486 | 'user' => 1, '--id' => [5, 13] 487 | ]); 488 | }); 489 | 490 | #### Passing Boolean Values 491 | 492 | If you need to specify the value of an option that does not accept string values, such as the `--force` flag on the `migrate:refresh` command, you should pass `true` or `false`: 493 | 494 | $exitCode = Artisan::call('migrate:refresh', [ 495 | '--force' => true, 496 | ]); 497 | 498 | 499 | ### Calling Commands From Other Commands 500 | 501 | Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the `call` method. This `call` method accepts the command name and an array of command parameters: 502 | 503 | /** 504 | * Execute the console command. 505 | * 506 | * @return mixed 507 | */ 508 | public function handle() 509 | { 510 | $this->call('email:send', [ 511 | 'user' => 1, '--queue' => 'default' 512 | ]); 513 | 514 | // 515 | } 516 | 517 | If you would like to call another console command and suppress all of its output, you may use the `callSilent` method. The `callSilent` method has the same signature as the `call` method: 518 | 519 | $this->callSilent('email:send', [ 520 | 'user' => 1, '--queue' => 'default' 521 | ]); 522 | 523 | 524 | ## Stub Customization 525 | 526 | The Artisan console's `make` commands are used to create a variety of classes, such as controllers, jobs, migrations, and tests. These classes are generated using "stub" files that are populated with values based on your input. However, you may sometimes wish to make small changes to files generated by Artisan. To accomplish this, you may use the `stub:publish` command to publish the most common stubs for customization: 527 | 528 | php artisan stub:publish 529 | 530 | The published stubs will be located within a `stubs` directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan `make` commands. 531 | -------------------------------------------------------------------------------- /tests/data/.docs/10.x/validation.md: -------------------------------------------------------------------------------- 1 | # Validation 2 | 3 | - [Introduction](#introduction) 4 | - [Validation Quickstart](#validation-quickstart) 5 | - [Defining The Routes](#quick-defining-the-routes) 6 | - [Creating The Controller](#quick-creating-the-controller) 7 | - [Writing The Validation Logic](#quick-writing-the-validation-logic) 8 | - [Displaying The Validation Errors](#quick-displaying-the-validation-errors) 9 | - [Repopulating Forms](#repopulating-forms) 10 | - [A Note On Optional Fields](#a-note-on-optional-fields) 11 | - [Validation Error Response Format](#validation-error-response-format) 12 | - [Form Request Validation](#form-request-validation) 13 | - [Creating Form Requests](#creating-form-requests) 14 | - [Authorizing Form Requests](#authorizing-form-requests) 15 | - [Customizing The Error Messages](#customizing-the-error-messages) 16 | - [Preparing Input For Validation](#preparing-input-for-validation) 17 | - [Manually Creating Validators](#manually-creating-validators) 18 | - [Automatic Redirection](#automatic-redirection) 19 | - [Named Error Bags](#named-error-bags) 20 | - [Customizing The Error Messages](#manual-customizing-the-error-messages) 21 | - [Performing Additional Validation](#performing-additional-validation) 22 | - [Working With Validated Input](#working-with-validated-input) 23 | - [Working With Error Messages](#working-with-error-messages) 24 | - [Specifying Custom Messages In Language Files](#specifying-custom-messages-in-language-files) 25 | - [Specifying Attributes In Language Files](#specifying-attribute-in-language-files) 26 | - [Specifying Values In Language Files](#specifying-values-in-language-files) 27 | - [Available Validation Rules](#available-validation-rules) 28 | - [Conditionally Adding Rules](#conditionally-adding-rules) 29 | - [Validating Arrays](#validating-arrays) 30 | - [Validating Nested Array Input](#validating-nested-array-input) 31 | - [Error Message Indexes & Positions](#error-message-indexes-and-positions) 32 | - [Validating Files](#validating-files) 33 | - [Validating Passwords](#validating-passwords) 34 | - [Custom Validation Rules](#custom-validation-rules) 35 | - [Using Rule Objects](#using-rule-objects) 36 | - [Using Closures](#using-closures) 37 | - [Implicit Rules](#implicit-rules) 38 | 39 | 40 | ## Introduction 41 | 42 | Laravel provides several different approaches to validate your application's incoming data. It is most common to use the `validate` method available on all incoming HTTP requests. However, we will discuss other approaches to validation as well. 43 | 44 | Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table. We'll cover each of these validation rules in detail so that you are familiar with all of Laravel's validation features. 45 | 46 | 47 | ## Validation Quickstart 48 | 49 | To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel: 50 | 51 | 52 | ### Defining The Routes 53 | 54 | First, let's assume we have the following routes defined in our `routes/web.php` file: 55 | 56 | use App\Http\Controllers\PostController; 57 | 58 | Route::get('/post/create', [PostController::class, 'create']); 59 | Route::post('/post', [PostController::class, 'store']); 60 | 61 | The `GET` route will display a form for the user to create a new blog post, while the `POST` route will store the new blog post in the database. 62 | 63 | 64 | ### Creating The Controller 65 | 66 | Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the `store` method empty for now: 67 | 68 | $post->id]); 97 | } 98 | } 99 | 100 | 101 | ### Writing The Validation Logic 102 | 103 | Now we are ready to fill in our `store` method with the logic to validate the new blog post. To do this, we will use the `validate` method provided by the `Illuminate\Http\Request` object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an `Illuminate\Validation\ValidationException` exception will be thrown and the proper error response will automatically be sent back to the user. 104 | 105 | If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a [JSON response containing the validation error messages](#validation-error-response-format) will be returned. 106 | 107 | To get a better understanding of the `validate` method, let's jump back into the `store` method: 108 | 109 | /** 110 | * Store a new blog post. 111 | */ 112 | public function store(Request $request): RedirectResponse 113 | { 114 | $validated = $request->validate([ 115 | 'title' => 'required|unique:posts|max:255', 116 | 'body' => 'required', 117 | ]); 118 | 119 | // The blog post is valid... 120 | 121 | return redirect('/posts'); 122 | } 123 | 124 | As you can see, the validation rules are passed into the `validate` method. Don't worry - all available validation rules are [documented](#available-validation-rules). Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally. 125 | 126 | Alternatively, validation rules may be specified as arrays of rules instead of a single `|` delimited string: 127 | 128 | $validatedData = $request->validate([ 129 | 'title' => ['required', 'unique:posts', 'max:255'], 130 | 'body' => ['required'], 131 | ]); 132 | 133 | In addition, you may use the `validateWithBag` method to validate a request and store any error messages within a [named error bag](#named-error-bags): 134 | 135 | $validatedData = $request->validateWithBag('post', [ 136 | 'title' => ['required', 'unique:posts', 'max:255'], 137 | 'body' => ['required'], 138 | ]); 139 | 140 | 141 | #### Stopping On First Validation Failure 142 | 143 | Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the `bail` rule to the attribute: 144 | 145 | $request->validate([ 146 | 'title' => 'bail|required|unique:posts|max:255', 147 | 'body' => 'required', 148 | ]); 149 | 150 | In this example, if the `unique` rule on the `title` attribute fails, the `max` rule will not be checked. Rules will be validated in the order they are assigned. 151 | 152 | 153 | #### A Note On Nested Attributes 154 | 155 | If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax: 156 | 157 | $request->validate([ 158 | 'title' => 'required|unique:posts|max:255', 159 | 'author.name' => 'required', 160 | 'author.description' => 'required', 161 | ]); 162 | 163 | On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as "dot" syntax by escaping the period with a backslash: 164 | 165 | $request->validate([ 166 | 'title' => 'required|unique:posts|max:255', 167 | 'v1\.0' => 'required', 168 | ]); 169 | 170 | 171 | ### Displaying The Validation Errors 172 | 173 | So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and [request input](/docs/{{version}}/requests#retrieving-old-input) will automatically be [flashed to the session](/docs/{{version}}/session#flash-data). 174 | 175 | An `$errors` variable is shared with all of your application's views by the `Illuminate\View\Middleware\ShareErrorsFromSession` middleware, which is provided by the `web` middleware group. When this middleware is applied an `$errors` variable will always be available in your views, allowing you to conveniently assume the `$errors` variable is always defined and can be safely used. The `$errors` variable will be an instance of `Illuminate\Support\MessageBag`. For more information on working with this object, [check out its documentation](#working-with-error-messages). 176 | 177 | So, in our example, the user will be redirected to our controller's `create` method when validation fails, allowing us to display the error messages in the view: 178 | 179 | ```blade 180 | 181 | 182 |

Create Post

183 | 184 | @if ($errors->any()) 185 |
186 |
    187 | @foreach ($errors->all() as $error) 188 |
  • {{ $error }}
  • 189 | @endforeach 190 |
191 |
192 | @endif 193 | 194 | 195 | ``` 196 | 197 | 198 | #### Customizing The Error Messages 199 | 200 | Laravel's built-in validation rules each have an error message that is located in your application's `lang/en/validation.php` file. If your application does not have a `lang` directory, you may instruct Laravel to create it using the `lang:publish` Artisan command. 201 | 202 | Within the `lang/en/validation.php` file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. 203 | 204 | In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). 205 | 206 | > **Warning** 207 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. 208 | 209 | 210 | #### XHR Requests & Validation 211 | 212 | In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the `validate` method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a [JSON response containing all of the validation errors](#validation-error-response-format). This JSON response will be sent with a 422 HTTP status code. 213 | 214 | 215 | #### The `@error` Directive 216 | 217 | You may use the `@error` [Blade](/docs/{{version}}/blade) directive to quickly determine if validation error messages exist for a given attribute. Within an `@error` directive, you may echo the `$message` variable to display the error message: 218 | 219 | ```blade 220 | 221 | 222 | 223 | 224 | 228 | 229 | @error('title') 230 |
{{ $message }}
231 | @enderror 232 | ``` 233 | 234 | If you are using [named error bags](#named-error-bags), you may pass the name of the error bag as the second argument to the `@error` directive: 235 | 236 | ```blade 237 | 238 | ``` 239 | 240 | 241 | ### Repopulating Forms 242 | 243 | When Laravel generates a redirect response due to a validation error, the framework will automatically [flash all of the request's input to the session](/docs/{{version}}/session#flash-data). This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit. 244 | 245 | To retrieve flashed input from the previous request, invoke the `old` method on an instance of `Illuminate\Http\Request`. The `old` method will pull the previously flashed input data from the [session](/docs/{{version}}/session): 246 | 247 | $title = $request->old('title'); 248 | 249 | Laravel also provides a global `old` helper. If you are displaying old input within a [Blade template](/docs/{{version}}/blade), it is more convenient to use the `old` helper to repopulate the form. If no old input exists for the given field, `null` will be returned: 250 | 251 | ```blade 252 | 253 | ``` 254 | 255 | 256 | ### A Note On Optional Fields 257 | 258 | By default, Laravel includes the `TrimStrings` and `ConvertEmptyStringsToNull` middleware in your application's global middleware stack. These middleware are listed in the stack by the `App\Http\Kernel` class. Because of this, you will often need to mark your "optional" request fields as `nullable` if you do not want the validator to consider `null` values as invalid. For example: 259 | 260 | $request->validate([ 261 | 'title' => 'required|unique:posts|max:255', 262 | 'body' => 'required', 263 | 'publish_at' => 'nullable|date', 264 | ]); 265 | 266 | In this example, we are specifying that the `publish_at` field may be either `null` or a valid date representation. If the `nullable` modifier is not added to the rule definition, the validator would consider `null` an invalid date. 267 | 268 | 269 | ### Validation Error Response Format 270 | 271 | When your application throws a `Illuminate\Validation\ValidationException` exception and the incoming HTTP request is expecting a JSON response, Laravel will automatically format the error messages for you and return a `422 Unprocessable Entity` HTTP response. 272 | 273 | Below, you can review an example of the JSON response format for validation errors. Note that nested error keys are flattened into "dot" notation format: 274 | 275 | ```json 276 | { 277 | "message": "The team name must be a string. (and 4 more errors)", 278 | "errors": { 279 | "team_name": [ 280 | "The team name must be a string.", 281 | "The team name must be at least 1 characters." 282 | ], 283 | "authorization.role": [ 284 | "The selected authorization.role is invalid." 285 | ], 286 | "users.0.email": [ 287 | "The users.0.email field is required." 288 | ], 289 | "users.2.email": [ 290 | "The users.2.email must be a valid email address." 291 | ] 292 | } 293 | } 294 | ``` 295 | 296 | 297 | ## Form Request Validation 298 | 299 | 300 | ### Creating Form Requests 301 | 302 | For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the `make:request` Artisan CLI command: 303 | 304 | ```shell 305 | php artisan make:request StorePostRequest 306 | ``` 307 | 308 | The generated form request class will be placed in the `app/Http/Requests` directory. If this directory does not exist, it will be created when you run the `make:request` command. Each form request generated by Laravel has two methods: `authorize` and `rules`. 309 | 310 | As you might have guessed, the `authorize` method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the `rules` method returns the validation rules that should apply to the request's data: 311 | 312 | /** 313 | * Get the validation rules that apply to the request. 314 | * 315 | * @return array 316 | */ 317 | public function rules(): array 318 | { 319 | return [ 320 | 'title' => 'required|unique:posts|max:255', 321 | 'body' => 'required', 322 | ]; 323 | } 324 | 325 | > **Note** 326 | > You may type-hint any dependencies you require within the `rules` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). 327 | 328 | So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic: 329 | 330 | /** 331 | * Store a new blog post. 332 | */ 333 | public function store(StorePostRequest $request): RedirectResponse 334 | { 335 | // The incoming request is valid... 336 | 337 | // Retrieve the validated input data... 338 | $validated = $request->validated(); 339 | 340 | // Retrieve a portion of the validated input data... 341 | $validated = $request->safe()->only(['name', 'email']); 342 | $validated = $request->safe()->except(['name', 'email']); 343 | 344 | // Store the blog post... 345 | 346 | return redirect('/posts'); 347 | } 348 | 349 | If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a [JSON representation of the validation errors](#validation-error-response-format). 350 | 351 | > **Note** 352 | > Need to add real-time form request validation to your Inertia powered Laravel frontend? Check out [Laravel Precognition](/docs/{{version}}/precognition). 353 | 354 | 355 | #### Performing Additional Validation 356 | 357 | Sometimes you need to perform additional validation after your initial validation is complete. You can accomplish this using the form request's `after` method. 358 | 359 | The `after` method should return an array of callables or closures which will be invoked after validation is complete. The given callables will receive an `Illuminate\Validation\Validator` instance, allowing you to raise additional error messages if necessary: 360 | 361 | use Illuminate\Validation\Validator; 362 | 363 | /** 364 | * Get the "after" validation callables for the request. 365 | */ 366 | public function after(): array 367 | { 368 | return [ 369 | function (Validator $validator) { 370 | if ($this->somethingElseIsInvalid()) { 371 | $validator->errors()->add( 372 | 'field', 373 | 'Something is wrong with this field!' 374 | ); 375 | } 376 | } 377 | ]; 378 | } 379 | 380 | As noted, the array returned by the `after` method may also contain invokable classes. The `__invoke` method of these classes will receive an `Illuminate\Validation\Validator` instance: 381 | 382 | ```php 383 | use App\Validation\ValidateShippingTime; 384 | use App\Validation\ValidateUserStatus; 385 | use Illuminate\Validation\Validator; 386 | 387 | /** 388 | * Get the "after" validation callables for the request. 389 | */ 390 | public function after(): array 391 | { 392 | return [ 393 | new ValidateUserStatus, 394 | new ValidateShippingTime, 395 | function (Validator $validator) { 396 | // 397 | } 398 | ]; 399 | } 400 | ``` 401 | 402 | 403 | #### Stopping On The First Validation Failure 404 | 405 | By adding a `stopOnFirstFailure` property to your request class, you may inform the validator that it should stop validating all attributes once a single validation failure has occurred: 406 | 407 | /** 408 | * Indicates if the validator should stop on the first rule failure. 409 | * 410 | * @var bool 411 | */ 412 | protected $stopOnFirstFailure = true; 413 | 414 | 415 | #### Customizing The Redirect Location 416 | 417 | As previously discussed, a redirect response will be generated to send the user back to their previous location when form request validation fails. However, you are free to customize this behavior. To do so, define a `$redirect` property on your form request: 418 | 419 | /** 420 | * The URI that users should be redirected to if validation fails. 421 | * 422 | * @var string 423 | */ 424 | protected $redirect = '/dashboard'; 425 | 426 | Or, if you would like to redirect users to a named route, you may define a `$redirectRoute` property instead: 427 | 428 | /** 429 | * The route that users should be redirected to if validation fails. 430 | * 431 | * @var string 432 | */ 433 | protected $redirectRoute = 'dashboard'; 434 | 435 | 436 | ### Authorizing Form Requests 437 | 438 | The form request class also contains an `authorize` method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your [authorization gates and policies](/docs/{{version}}/authorization) within this method: 439 | 440 | use App\Models\Comment; 441 | 442 | /** 443 | * Determine if the user is authorized to make this request. 444 | */ 445 | public function authorize(): bool 446 | { 447 | $comment = Comment::find($this->route('comment')); 448 | 449 | return $comment && $this->user()->can('update', $comment); 450 | } 451 | 452 | Since all form requests extend the base Laravel request class, we may use the `user` method to access the currently authenticated user. Also, note the call to the `route` method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the `{comment}` parameter in the example below: 453 | 454 | Route::post('/comment/{comment}'); 455 | 456 | Therefore, if your application is taking advantage of [route model binding](/docs/{{version}}/routing#route-model-binding), your code may be made even more succinct by accessing the resolved model as a property of the request: 457 | 458 | return $this->user()->can('update', $this->comment); 459 | 460 | If the `authorize` method returns `false`, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute. 461 | 462 | If you plan to handle authorization logic for the request in another part of your application, you may simply return `true` from the `authorize` method: 463 | 464 | /** 465 | * Determine if the user is authorized to make this request. 466 | */ 467 | public function authorize(): bool 468 | { 469 | return true; 470 | } 471 | 472 | > **Note** 473 | > You may type-hint any dependencies you need within the `authorize` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). 474 | 475 | 476 | ### Customizing The Error Messages 477 | 478 | You may customize the error messages used by the form request by overriding the `messages` method. This method should return an array of attribute / rule pairs and their corresponding error messages: 479 | 480 | /** 481 | * Get the error messages for the defined validation rules. 482 | * 483 | * @return array 484 | */ 485 | public function messages(): array 486 | { 487 | return [ 488 | 'title.required' => 'A title is required', 489 | 'body.required' => 'A message is required', 490 | ]; 491 | } 492 | 493 | 494 | #### Customizing The Validation Attributes 495 | 496 | Many of Laravel's built-in validation rule error messages contain an `:attribute` placeholder. If you would like the `:attribute` placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the `attributes` method. This method should return an array of attribute / name pairs: 497 | 498 | /** 499 | * Get custom attributes for validator errors. 500 | * 501 | * @return array 502 | */ 503 | public function attributes(): array 504 | { 505 | return [ 506 | 'email' => 'email address', 507 | ]; 508 | } 509 | 510 | 511 | ### Preparing Input For Validation 512 | 513 | If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the `prepareForValidation` method: 514 | 515 | use Illuminate\Support\Str; 516 | 517 | /** 518 | * Prepare the data for validation. 519 | */ 520 | protected function prepareForValidation(): void 521 | { 522 | $this->merge([ 523 | 'slug' => Str::slug($this->slug), 524 | ]); 525 | } 526 | 527 | Likewise, if you need to normalize any request data after validation is complete, you may use the `passedValidation` method: 528 | 529 | /** 530 | * Handle a passed validation attempt. 531 | */ 532 | protected function passedValidation(): void 533 | { 534 | $this->replace(['name' => 'Taylor']); 535 | } 536 | 537 | 538 | ## Manually Creating Validators 539 | 540 | If you do not want to use the `validate` method on the request, you may create a validator instance manually using the `Validator` [facade](/docs/{{version}}/facades). The `make` method on the facade generates a new validator instance: 541 | 542 | all(), [ 559 | 'title' => 'required|unique:posts|max:255', 560 | 'body' => 'required', 561 | ]); 562 | 563 | if ($validator->fails()) { 564 | return redirect('post/create') 565 | ->withErrors($validator) 566 | ->withInput(); 567 | } 568 | 569 | // Retrieve the validated input... 570 | $validated = $validator->validated(); 571 | 572 | // Retrieve a portion of the validated input... 573 | $validated = $validator->safe()->only(['name', 'email']); 574 | $validated = $validator->safe()->except(['name', 'email']); 575 | 576 | // Store the blog post... 577 | 578 | return redirect('/posts'); 579 | } 580 | } 581 | 582 | The first argument passed to the `make` method is the data under validation. The second argument is an array of the validation rules that should be applied to the data. 583 | 584 | After determining whether the request validation failed, you may use the `withErrors` method to flash the error messages to the session. When using this method, the `$errors` variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The `withErrors` method accepts a validator, a `MessageBag`, or a PHP `array`. 585 | 586 | #### Stopping On First Validation Failure 587 | 588 | The `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred: 589 | 590 | if ($validator->stopOnFirstFailure()->fails()) { 591 | // ... 592 | } 593 | 594 | 595 | ### Automatic Redirection 596 | 597 | If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's `validate` method, you may call the `validate` method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a [JSON response will be returned](#validation-error-response-format): 598 | 599 | Validator::make($request->all(), [ 600 | 'title' => 'required|unique:posts|max:255', 601 | 'body' => 'required', 602 | ])->validate(); 603 | 604 | You may use the `validateWithBag` method to store the error messages in a [named error bag](#named-error-bags) if validation fails: 605 | 606 | Validator::make($request->all(), [ 607 | 'title' => 'required|unique:posts|max:255', 608 | 'body' => 'required', 609 | ])->validateWithBag('post'); 610 | 611 | 612 | ### Named Error Bags 613 | 614 | If you have multiple forms on a single page, you may wish to name the `MessageBag` containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to `withErrors`: 615 | 616 | return redirect('register')->withErrors($validator, 'login'); 617 | 618 | You may then access the named `MessageBag` instance from the `$errors` variable: 619 | 620 | ```blade 621 | {{ $errors->login->first('email') }} 622 | ``` 623 | 624 | 625 | ### Customizing The Error Messages 626 | 627 | If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the `Validator::make` method: 628 | 629 | $validator = Validator::make($input, $rules, $messages = [ 630 | 'required' => 'The :attribute field is required.', 631 | ]); 632 | 633 | In this example, the `:attribute` placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example: 634 | 635 | $messages = [ 636 | 'same' => 'The :attribute and :other must match.', 637 | 'size' => 'The :attribute must be exactly :size.', 638 | 'between' => 'The :attribute value :input is not between :min - :max.', 639 | 'in' => 'The :attribute must be one of the following types: :values', 640 | ]; 641 | 642 | 643 | #### Specifying A Custom Message For A Given Attribute 644 | 645 | Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule: 646 | 647 | $messages = [ 648 | 'email.required' => 'We need to know your email address!', 649 | ]; 650 | 651 | 652 | #### Specifying Custom Attribute Values 653 | 654 | Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the `Validator::make` method: 655 | 656 | $validator = Validator::make($input, $rules, $messages, [ 657 | 'email' => 'email address', 658 | ]); 659 | 660 | 661 | ### Performing Additional Validation 662 | 663 | Sometimes you need to perform additional validation after your initial validation is complete. You can accomplish this using the validator's `after` method. The `after` method accepts a closure or an array of callables which will be invoked after validation is complete. The given callables will receive an `Illuminate\Validation\Validator` instance, allowing you to raise additional error messages if necessary: 664 | 665 | use Illuminate\Support\Facades\Validator; 666 | 667 | $validator = Validator::make(/* ... */); 668 | 669 | $validator->after(function ($validator) { 670 | if ($this->somethingElseIsInvalid()) { 671 | $validator->errors()->add( 672 | 'field', 'Something is wrong with this field!' 673 | ); 674 | } 675 | }); 676 | 677 | if ($validator->fails()) { 678 | // ... 679 | } 680 | 681 | As noted, the `after` method also accepts an array of callables, which is particularly convenient if your "after validation" logic is encapsulated in invokable classes, which will receive an `Illuminate\Validation\Validator` instance via their `__invoke` method: 682 | 683 | ```php 684 | use App\Validation\ValidateShippingTime; 685 | use App\Validation\ValidateUserStatus; 686 | 687 | $validator->after([ 688 | new ValidateUserStatus, 689 | new ValidateShippingTime, 690 | function ($validator) { 691 | // ... 692 | }, 693 | ]); 694 | ``` 695 | 696 | 697 | ## Working With Validated Input 698 | 699 | After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the `validated` method on a form request or validator instance. This method returns an array of the data that was validated: 700 | 701 | $validated = $request->validated(); 702 | 703 | $validated = $validator->validated(); 704 | 705 | Alternatively, you may call the `safe` method on a form request or validator instance. This method returns an instance of `Illuminate\Support\ValidatedInput`. This object exposes `only`, `except`, and `all` methods to retrieve a subset of the validated data or the entire array of validated data: 706 | 707 | $validated = $request->safe()->only(['name', 'email']); 708 | 709 | $validated = $request->safe()->except(['name', 'email']); 710 | 711 | $validated = $request->safe()->all(); 712 | 713 | In addition, the `Illuminate\Support\ValidatedInput` instance may be iterated over and accessed like an array: 714 | 715 | // Validated data may be iterated... 716 | foreach ($request->safe() as $key => $value) { 717 | // ... 718 | } 719 | 720 | // Validated data may be accessed as an array... 721 | $validated = $request->safe(); 722 | 723 | $email = $validated['email']; 724 | 725 | If you would like to add additional fields to the validated data, you may call the `merge` method: 726 | 727 | $validated = $request->safe()->merge(['name' => 'Taylor Otwell']); 728 | 729 | If you would like to retrieve the validated data as a [collection](/docs/{{version}}/collections) instance, you may call the `collect` method: 730 | 731 | $collection = $request->safe()->collect(); 732 | 733 | 734 | ## Working With Error Messages 735 | 736 | After calling the `errors` method on a `Validator` instance, you will receive an `Illuminate\Support\MessageBag` instance, which has a variety of convenient methods for working with error messages. The `$errors` variable that is automatically made available to all views is also an instance of the `MessageBag` class. 737 | 738 | 739 | #### Retrieving The First Error Message For A Field 740 | 741 | To retrieve the first error message for a given field, use the `first` method: 742 | 743 | $errors = $validator->errors(); 744 | 745 | echo $errors->first('email'); 746 | 747 | 748 | #### Retrieving All Error Messages For A Field 749 | 750 | If you need to retrieve an array of all the messages for a given field, use the `get` method: 751 | 752 | foreach ($errors->get('email') as $message) { 753 | // ... 754 | } 755 | 756 | If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the `*` character: 757 | 758 | foreach ($errors->get('attachments.*') as $message) { 759 | // ... 760 | } 761 | 762 | 763 | #### Retrieving All Error Messages For All Fields 764 | 765 | To retrieve an array of all messages for all fields, use the `all` method: 766 | 767 | foreach ($errors->all() as $message) { 768 | // ... 769 | } 770 | 771 | 772 | #### Determining If Messages Exist For A Field 773 | 774 | The `has` method may be used to determine if any error messages exist for a given field: 775 | 776 | if ($errors->has('email')) { 777 | // ... 778 | } 779 | 780 | 781 | ### Specifying Custom Messages In Language Files 782 | 783 | Laravel's built-in validation rules each have an error message that is located in your application's `lang/en/validation.php` file. If your application does not have a `lang` directory, you may instruct Laravel to create it using the `lang:publish` Artisan command. 784 | 785 | Within the `lang/en/validation.php` file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. 786 | 787 | In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). 788 | 789 | > **Warning** 790 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. 791 | 792 | 793 | #### Custom Messages For Specific Attributes 794 | 795 | You may customize the error messages used for specified attribute and rule combinations within your application's validation language files. To do so, add your message customizations to the `custom` array of your application's `lang/xx/validation.php` language file: 796 | 797 | 'custom' => [ 798 | 'email' => [ 799 | 'required' => 'We need to know your email address!', 800 | 'max' => 'Your email address is too long!' 801 | ], 802 | ], 803 | 804 | 805 | ### Specifying Attributes In Language Files 806 | 807 | Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. If you would like the `:attribute` portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the `attributes` array of your `lang/xx/validation.php` language file: 808 | 809 | 'attributes' => [ 810 | 'email' => 'email address', 811 | ], 812 | 813 | > **Warning** 814 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. 815 | 816 | 817 | ### Specifying Values In Language Files 818 | 819 | Some of Laravel's built-in validation rule error messages contain a `:value` placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the `:value` portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the `payment_type` has a value of `cc`: 820 | 821 | Validator::make($request->all(), [ 822 | 'credit_card_number' => 'required_if:payment_type,cc' 823 | ]); 824 | 825 | If this validation rule fails, it will produce the following error message: 826 | 827 | ```none 828 | The credit card number field is required when payment type is cc. 829 | ``` 830 | 831 | Instead of displaying `cc` as the payment type value, you may specify a more user-friendly value representation in your `lang/xx/validation.php` language file by defining a `values` array: 832 | 833 | 'values' => [ 834 | 'payment_type' => [ 835 | 'cc' => 'credit card' 836 | ], 837 | ], 838 | 839 | > **Warning** 840 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. 841 | 842 | After defining this value, the validation rule will produce the following error message: 843 | 844 | ```none 845 | The credit card number field is required when payment type is credit card. 846 | ``` 847 | 848 | 849 | ## Available Validation Rules 850 | 851 | Below is a list of all available validation rules and their function: 852 | 853 | 865 | 866 |
867 | 868 | [Accepted](#rule-accepted) 869 | [Accepted If](#rule-accepted-if) 870 | [Active URL](#rule-active-url) 871 | [After (Date)](#rule-after) 872 | [After Or Equal (Date)](#rule-after-or-equal) 873 | [Alpha](#rule-alpha) 874 | [Alpha Dash](#rule-alpha-dash) 875 | [Alpha Numeric](#rule-alpha-num) 876 | [Array](#rule-array) 877 | [Ascii](#rule-ascii) 878 | [Bail](#rule-bail) 879 | [Before (Date)](#rule-before) 880 | [Before Or Equal (Date)](#rule-before-or-equal) 881 | [Between](#rule-between) 882 | [Boolean](#rule-boolean) 883 | [Confirmed](#rule-confirmed) 884 | [Current Password](#rule-current-password) 885 | [Date](#rule-date) 886 | [Date Equals](#rule-date-equals) 887 | [Date Format](#rule-date-format) 888 | [Decimal](#rule-decimal) 889 | [Declined](#rule-declined) 890 | [Declined If](#rule-declined-if) 891 | [Different](#rule-different) 892 | [Digits](#rule-digits) 893 | [Digits Between](#rule-digits-between) 894 | [Dimensions (Image Files)](#rule-dimensions) 895 | [Distinct](#rule-distinct) 896 | [Doesnt Start With](#rule-doesnt-start-with) 897 | [Doesnt End With](#rule-doesnt-end-with) 898 | [Email](#rule-email) 899 | [Ends With](#rule-ends-with) 900 | [Enum](#rule-enum) 901 | [Exclude](#rule-exclude) 902 | [Exclude If](#rule-exclude-if) 903 | [Exclude Unless](#rule-exclude-unless) 904 | [Exclude With](#rule-exclude-with) 905 | [Exclude Without](#rule-exclude-without) 906 | [Exists (Database)](#rule-exists) 907 | [File](#rule-file) 908 | [Filled](#rule-filled) 909 | [Greater Than](#rule-gt) 910 | [Greater Than Or Equal](#rule-gte) 911 | [Image (File)](#rule-image) 912 | [In](#rule-in) 913 | [In Array](#rule-in-array) 914 | [Integer](#rule-integer) 915 | [IP Address](#rule-ip) 916 | [JSON](#rule-json) 917 | [Less Than](#rule-lt) 918 | [Less Than Or Equal](#rule-lte) 919 | [Lowercase](#rule-lowercase) 920 | [MAC Address](#rule-mac) 921 | [Max](#rule-max) 922 | [Max Digits](#rule-max-digits) 923 | [MIME Types](#rule-mimetypes) 924 | [MIME Type By File Extension](#rule-mimes) 925 | [Min](#rule-min) 926 | [Min Digits](#rule-min-digits) 927 | [Missing](#rule-missing) 928 | [Missing If](#rule-missing-if) 929 | [Missing Unless](#rule-missing-unless) 930 | [Missing With](#rule-missing-with) 931 | [Missing With All](#rule-missing-with-all) 932 | [Multiple Of](#rule-multiple-of) 933 | [Not In](#rule-not-in) 934 | [Not Regex](#rule-not-regex) 935 | [Nullable](#rule-nullable) 936 | [Numeric](#rule-numeric) 937 | [Password](#rule-password) 938 | [Present](#rule-present) 939 | [Prohibited](#rule-prohibited) 940 | [Prohibited If](#rule-prohibited-if) 941 | [Prohibited Unless](#rule-prohibited-unless) 942 | [Prohibits](#rule-prohibits) 943 | [Regular Expression](#rule-regex) 944 | [Required](#rule-required) 945 | [Required If](#rule-required-if) 946 | [Required Unless](#rule-required-unless) 947 | [Required With](#rule-required-with) 948 | [Required With All](#rule-required-with-all) 949 | [Required Without](#rule-required-without) 950 | [Required Without All](#rule-required-without-all) 951 | [Required Array Keys](#rule-required-array-keys) 952 | [Same](#rule-same) 953 | [Size](#rule-size) 954 | [Sometimes](#validating-when-present) 955 | [Starts With](#rule-starts-with) 956 | [String](#rule-string) 957 | [Timezone](#rule-timezone) 958 | [Unique (Database)](#rule-unique) 959 | [Uppercase](#rule-uppercase) 960 | [URL](#rule-url) 961 | [ULID](#rule-ulid) 962 | [UUID](#rule-uuid) 963 | 964 |
965 | 966 | 967 | #### accepted 968 | 969 | The field under validation must be `"yes"`, `"on"`, `1`, or `true`. This is useful for validating "Terms of Service" acceptance or similar fields. 970 | 971 | 972 | #### accepted_if:anotherfield,value,... 973 | 974 | The field under validation must be `"yes"`, `"on"`, `1`, or `true` if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields. 975 | 976 | 977 | #### active_url 978 | 979 | The field under validation must have a valid A or AAAA record according to the `dns_get_record` PHP function. The hostname of the provided URL is extracted using the `parse_url` PHP function before being passed to `dns_get_record`. 980 | 981 | 982 | #### after:_date_ 983 | 984 | The field under validation must be a value after a given date. The dates will be passed into the `strtotime` PHP function in order to be converted to a valid `DateTime` instance: 985 | 986 | 'start_date' => 'required|date|after:tomorrow' 987 | 988 | Instead of passing a date string to be evaluated by `strtotime`, you may specify another field to compare against the date: 989 | 990 | 'finish_date' => 'required|date|after:start_date' 991 | 992 | 993 | #### after\_or\_equal:_date_ 994 | 995 | The field under validation must be a value after or equal to the given date. For more information, see the [after](#rule-after) rule. 996 | 997 | 998 | #### alpha 999 | 1000 | The field under validation must be entirely Unicode alphabetic characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=) and [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=). 1001 | 1002 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule: 1003 | 1004 | ```php 1005 | 'username' => 'alpha:ascii', 1006 | ``` 1007 | 1008 | 1009 | #### alpha_dash 1010 | 1011 | The field under validation must be entirely Unicode alpha-numeric characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), [`\p{N}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=), as well as ASCII dashes (`-`) and ASCII underscores (`_`). 1012 | 1013 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule: 1014 | 1015 | ```php 1016 | 'username' => 'alpha_dash:ascii', 1017 | ``` 1018 | 1019 | 1020 | #### alpha_num 1021 | 1022 | The field under validation must be entirely Unicode alpha-numeric characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), and [`\p{N}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=). 1023 | 1024 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule: 1025 | 1026 | ```php 1027 | 'username' => 'alpha_num:ascii', 1028 | ``` 1029 | 1030 | 1031 | #### array 1032 | 1033 | The field under validation must be a PHP `array`. 1034 | 1035 | When additional values are provided to the `array` rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the `admin` key in the input array is invalid since it is not contained in the list of values provided to the `array` rule: 1036 | 1037 | use Illuminate\Support\Facades\Validator; 1038 | 1039 | $input = [ 1040 | 'user' => [ 1041 | 'name' => 'Taylor Otwell', 1042 | 'username' => 'taylorotwell', 1043 | 'admin' => true, 1044 | ], 1045 | ]; 1046 | 1047 | Validator::make($input, [ 1048 | 'user' => 'array:name,username', 1049 | ]); 1050 | 1051 | In general, you should always specify the array keys that are allowed to be present within your array. 1052 | 1053 | 1054 | #### ascii 1055 | 1056 | The field under validation must be entirely 7-bit ASCII characters. 1057 | 1058 | 1059 | #### bail 1060 | 1061 | Stop running validation rules for the field after the first validation failure. 1062 | 1063 | While the `bail` rule will only stop validating a specific field when it encounters a validation failure, the `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred: 1064 | 1065 | if ($validator->stopOnFirstFailure()->fails()) { 1066 | // ... 1067 | } 1068 | 1069 | 1070 | #### before:_date_ 1071 | 1072 | The field under validation must be a value preceding the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. 1073 | 1074 | 1075 | #### before\_or\_equal:_date_ 1076 | 1077 | The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. 1078 | 1079 | 1080 | #### between:_min_,_max_ 1081 | 1082 | The field under validation must have a size between the given _min_ and _max_ (inclusive). Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. 1083 | 1084 | 1085 | #### boolean 1086 | 1087 | The field under validation must be able to be cast as a boolean. Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`. 1088 | 1089 | 1090 | #### confirmed 1091 | 1092 | The field under validation must have a matching field of `{field}_confirmation`. For example, if the field under validation is `password`, a matching `password_confirmation` field must be present in the input. 1093 | 1094 | 1095 | #### current_password 1096 | 1097 | The field under validation must match the authenticated user's password. You may specify an [authentication guard](/docs/{{version}}/authentication) using the rule's first parameter: 1098 | 1099 | 'password' => 'current_password:api' 1100 | 1101 | 1102 | #### date 1103 | 1104 | The field under validation must be a valid, non-relative date according to the `strtotime` PHP function. 1105 | 1106 | 1107 | #### date_equals:_date_ 1108 | 1109 | The field under validation must be equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. 1110 | 1111 | 1112 | #### date_format:_format_,... 1113 | 1114 | The field under validation must match one of the given _formats_. You should use **either** `date` or `date_format` when validating a field, not both. This validation rule supports all formats supported by PHP's [DateTime](https://www.php.net/manual/en/class.datetime.php) class. 1115 | 1116 | 1117 | #### decimal:_min_,_max_ 1118 | 1119 | The field under validation must be numeric and must contain the specified number of decimal places: 1120 | 1121 | // Must have exactly two decimal places (9.99)... 1122 | 'price' => 'decimal:2' 1123 | 1124 | // Must have between 2 and 4 decimal places... 1125 | 'price' => 'decimal:2,4' 1126 | 1127 | 1128 | #### declined 1129 | 1130 | The field under validation must be `"no"`, `"off"`, `0`, or `false`. 1131 | 1132 | 1133 | #### declined_if:anotherfield,value,... 1134 | 1135 | The field under validation must be `"no"`, `"off"`, `0`, or `false` if another field under validation is equal to a specified value. 1136 | 1137 | 1138 | #### different:_field_ 1139 | 1140 | The field under validation must have a different value than _field_. 1141 | 1142 | 1143 | #### digits:_value_ 1144 | 1145 | The integer under validation must have an exact length of _value_. 1146 | 1147 | 1148 | #### digits_between:_min_,_max_ 1149 | 1150 | The integer validation must have a length between the given _min_ and _max_. 1151 | 1152 | 1153 | #### dimensions 1154 | 1155 | The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters: 1156 | 1157 | 'avatar' => 'dimensions:min_width=100,min_height=200' 1158 | 1159 | Available constraints are: _min\_width_, _max\_width_, _min\_height_, _max\_height_, _width_, _height_, _ratio_. 1160 | 1161 | A _ratio_ constraint should be represented as width divided by height. This can be specified either by a fraction like `3/2` or a float like `1.5`: 1162 | 1163 | 'avatar' => 'dimensions:ratio=3/2' 1164 | 1165 | Since this rule requires several arguments, you may use the `Rule::dimensions` method to fluently construct the rule: 1166 | 1167 | use Illuminate\Support\Facades\Validator; 1168 | use Illuminate\Validation\Rule; 1169 | 1170 | Validator::make($data, [ 1171 | 'avatar' => [ 1172 | 'required', 1173 | Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2), 1174 | ], 1175 | ]); 1176 | 1177 | 1178 | #### distinct 1179 | 1180 | When validating arrays, the field under validation must not have any duplicate values: 1181 | 1182 | 'foo.*.id' => 'distinct' 1183 | 1184 | Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the `strict` parameter to your validation rule definition: 1185 | 1186 | 'foo.*.id' => 'distinct:strict' 1187 | 1188 | You may add `ignore_case` to the validation rule's arguments to make the rule ignore capitalization differences: 1189 | 1190 | 'foo.*.id' => 'distinct:ignore_case' 1191 | 1192 | 1193 | #### doesnt_start_with:_foo_,_bar_,... 1194 | 1195 | The field under validation must not start with one of the given values. 1196 | 1197 | 1198 | #### doesnt_end_with:_foo_,_bar_,... 1199 | 1200 | The field under validation must not end with one of the given values. 1201 | 1202 | 1203 | #### email 1204 | 1205 | The field under validation must be formatted as an email address. This validation rule utilizes the [`egulias/email-validator`](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well: 1206 | 1207 | 'email' => 'email:rfc,dns' 1208 | 1209 | The example above will apply the `RFCValidation` and `DNSCheckValidation` validations. Here's a full list of validation styles you can apply: 1210 | 1211 |
1212 | 1213 | - `rfc`: `RFCValidation` 1214 | - `strict`: `NoRFCWarningsValidation` 1215 | - `dns`: `DNSCheckValidation` 1216 | - `spoof`: `SpoofCheckValidation` 1217 | - `filter`: `FilterEmailValidation` 1218 | - `filter_unicode`: `FilterEmailValidation::unicode()` 1219 | 1220 |
1221 | 1222 | The `filter` validator, which uses PHP's `filter_var` function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8. 1223 | 1224 | > **Warning** 1225 | > The `dns` and `spoof` validators require the PHP `intl` extension. 1226 | 1227 | 1228 | #### ends_with:_foo_,_bar_,... 1229 | 1230 | The field under validation must end with one of the given values. 1231 | 1232 | 1233 | #### enum 1234 | 1235 | The `Enum` rule is a class based rule that validates whether the field under validation contains a valid enum value. The `Enum` rule accepts the name of the enum as its only constructor argument: 1236 | 1237 | use App\Enums\ServerStatus; 1238 | use Illuminate\Validation\Rules\Enum; 1239 | 1240 | $request->validate([ 1241 | 'status' => [new Enum(ServerStatus::class)], 1242 | ]); 1243 | 1244 | 1245 | #### exclude 1246 | 1247 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods. 1248 | 1249 | 1250 | #### exclude_if:_anotherfield_,_value_ 1251 | 1252 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is equal to _value_. 1253 | 1254 | If complex conditional exclusion logic is required, you may utilize the `Rule::excludeIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be excluded: 1255 | 1256 | use Illuminate\Support\Facades\Validator; 1257 | use Illuminate\Validation\Rule; 1258 | 1259 | Validator::make($request->all(), [ 1260 | 'role_id' => Rule::excludeIf($request->user()->is_admin), 1261 | ]); 1262 | 1263 | Validator::make($request->all(), [ 1264 | 'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin), 1265 | ]); 1266 | 1267 | 1268 | #### exclude_unless:_anotherfield_,_value_ 1269 | 1270 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods unless _anotherfield_'s field is equal to _value_. If _value_ is `null` (`exclude_unless:name,null`), the field under validation will be excluded unless the comparison field is `null` or the comparison field is missing from the request data. 1271 | 1272 | 1273 | #### exclude_with:_anotherfield_ 1274 | 1275 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is present. 1276 | 1277 | 1278 | #### exclude_without:_anotherfield_ 1279 | 1280 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is not present. 1281 | 1282 | 1283 | #### exists:_table_,_column_ 1284 | 1285 | The field under validation must exist in a given database table. 1286 | 1287 | 1288 | #### Basic Usage Of Exists Rule 1289 | 1290 | 'state' => 'exists:states' 1291 | 1292 | If the `column` option is not specified, the field name will be used. So, in this case, the rule will validate that the `states` database table contains a record with a `state` column value matching the request's `state` attribute value. 1293 | 1294 | 1295 | #### Specifying A Custom Column Name 1296 | 1297 | You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name: 1298 | 1299 | 'state' => 'exists:states,abbreviation' 1300 | 1301 | Occasionally, you may need to specify a specific database connection to be used for the `exists` query. You can accomplish this by prepending the connection name to the table name: 1302 | 1303 | 'email' => 'exists:connection.staff,email' 1304 | 1305 | Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name: 1306 | 1307 | 'user_id' => 'exists:App\Models\User,id' 1308 | 1309 | If you would like to customize the query executed by the validation rule, you may use the `Rule` class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the `|` character to delimit them: 1310 | 1311 | use Illuminate\Database\Query\Builder; 1312 | use Illuminate\Support\Facades\Validator; 1313 | use Illuminate\Validation\Rule; 1314 | 1315 | Validator::make($data, [ 1316 | 'email' => [ 1317 | 'required', 1318 | Rule::exists('staff')->where(function (Builder $query) { 1319 | return $query->where('account_id', 1); 1320 | }), 1321 | ], 1322 | ]); 1323 | 1324 | You may explicitly specify the database column name that should be used by the `exists` rule generated by the `Rule::exists` method by providing the column name as the second argument to the `exists` method: 1325 | 1326 | 'state' => Rule::exists('states', 'abbreviation'), 1327 | 1328 | 1329 | #### file 1330 | 1331 | The field under validation must be a successfully uploaded file. 1332 | 1333 | 1334 | #### filled 1335 | 1336 | The field under validation must not be empty when it is present. 1337 | 1338 | 1339 | #### gt:_field_ 1340 | 1341 | The field under validation must be greater than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. 1342 | 1343 | 1344 | #### gte:_field_ 1345 | 1346 | The field under validation must be greater than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. 1347 | 1348 | 1349 | #### image 1350 | 1351 | The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp). 1352 | 1353 | 1354 | #### in:_foo_,_bar_,... 1355 | 1356 | The field under validation must be included in the given list of values. Since this rule often requires you to `implode` an array, the `Rule::in` method may be used to fluently construct the rule: 1357 | 1358 | use Illuminate\Support\Facades\Validator; 1359 | use Illuminate\Validation\Rule; 1360 | 1361 | Validator::make($data, [ 1362 | 'zones' => [ 1363 | 'required', 1364 | Rule::in(['first-zone', 'second-zone']), 1365 | ], 1366 | ]); 1367 | 1368 | When the `in` rule is combined with the `array` rule, each value in the input array must be present within the list of values provided to the `in` rule. In the following example, the `LAS` airport code in the input array is invalid since it is not contained in the list of airports provided to the `in` rule: 1369 | 1370 | use Illuminate\Support\Facades\Validator; 1371 | use Illuminate\Validation\Rule; 1372 | 1373 | $input = [ 1374 | 'airports' => ['NYC', 'LAS'], 1375 | ]; 1376 | 1377 | Validator::make($input, [ 1378 | 'airports' => [ 1379 | 'required', 1380 | 'array', 1381 | ], 1382 | 'airports.*' => Rule::in(['NYC', 'LIT']), 1383 | ]); 1384 | 1385 | 1386 | #### in_array:_anotherfield_.* 1387 | 1388 | The field under validation must exist in _anotherfield_'s values. 1389 | 1390 | 1391 | #### integer 1392 | 1393 | The field under validation must be an integer. 1394 | 1395 | > **Warning** 1396 | > This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's `FILTER_VALIDATE_INT` rule. If you need to validate the input as being a number please use this rule in combination with [the `numeric` validation rule](#rule-numeric). 1397 | 1398 | 1399 | #### ip 1400 | 1401 | The field under validation must be an IP address. 1402 | 1403 | 1404 | #### ipv4 1405 | 1406 | The field under validation must be an IPv4 address. 1407 | 1408 | 1409 | #### ipv6 1410 | 1411 | The field under validation must be an IPv6 address. 1412 | 1413 | 1414 | #### json 1415 | 1416 | The field under validation must be a valid JSON string. 1417 | 1418 | 1419 | #### lt:_field_ 1420 | 1421 | The field under validation must be less than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. 1422 | 1423 | 1424 | #### lte:_field_ 1425 | 1426 | The field under validation must be less than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. 1427 | 1428 | 1429 | #### lowercase 1430 | 1431 | The field under validation must be lowercase. 1432 | 1433 | 1434 | #### mac_address 1435 | 1436 | The field under validation must be a MAC address. 1437 | 1438 | 1439 | #### max:_value_ 1440 | 1441 | The field under validation must be less than or equal to a maximum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. 1442 | 1443 | 1444 | #### max_digits:_value_ 1445 | 1446 | The integer under validation must have a maximum length of _value_. 1447 | 1448 | 1449 | #### mimetypes:_text/plain_,... 1450 | 1451 | The file under validation must match one of the given MIME types: 1452 | 1453 | 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime' 1454 | 1455 | To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client's provided MIME type. 1456 | 1457 | 1458 | #### mimes:_foo_,_bar_,... 1459 | 1460 | The file under validation must have a MIME type corresponding to one of the listed extensions. 1461 | 1462 | 1463 | #### Basic Usage Of MIME Rule 1464 | 1465 | 'photo' => 'mimes:jpg,bmp,png' 1466 | 1467 | Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location: 1468 | 1469 | [https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) 1470 | 1471 | 1472 | #### min:_value_ 1473 | 1474 | The field under validation must have a minimum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. 1475 | 1476 | 1477 | #### min_digits:_value_ 1478 | 1479 | The integer under validation must have a minimum length of _value_. 1480 | 1481 | 1482 | #### multiple_of:_value_ 1483 | 1484 | The field under validation must be a multiple of _value_. 1485 | 1486 | 1487 | #### missing 1488 | 1489 | The field under validation must not be present in the input data. 1490 | 1491 | 1492 | #### missing_if:_anotherfield_,_value_,... 1493 | 1494 | The field under validation must not be present if the _anotherfield_ field is equal to any _value_. 1495 | 1496 | 1497 | #### missing_unless:_anotherfield_,_value_ 1498 | 1499 | The field under validation must not be present unless the _anotherfield_ field is equal to any _value_. 1500 | 1501 | 1502 | #### missing_with:_foo_,_bar_,... 1503 | 1504 | The field under validation must not be present _only if_ any of the other specified fields are present. 1505 | 1506 | 1507 | #### missing_with_all:_foo_,_bar_,... 1508 | 1509 | The field under validation must not be present _only if_ all of the other specified fields are present. 1510 | 1511 | 1512 | #### not_in:_foo_,_bar_,... 1513 | 1514 | The field under validation must not be included in the given list of values. The `Rule::notIn` method may be used to fluently construct the rule: 1515 | 1516 | use Illuminate\Validation\Rule; 1517 | 1518 | Validator::make($data, [ 1519 | 'toppings' => [ 1520 | 'required', 1521 | Rule::notIn(['sprinkles', 'cherries']), 1522 | ], 1523 | ]); 1524 | 1525 | 1526 | #### not_regex:_pattern_ 1527 | 1528 | The field under validation must not match the given regular expression. 1529 | 1530 | Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'not_regex:/^.+$/i'`. 1531 | 1532 | > **Warning** 1533 | > When using the `regex` / `not_regex` patterns, it may be necessary to specify your validation rules using an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. 1534 | 1535 | 1536 | #### nullable 1537 | 1538 | The field under validation may be `null`. 1539 | 1540 | 1541 | #### numeric 1542 | 1543 | The field under validation must be [numeric](https://www.php.net/manual/en/function.is-numeric.php). 1544 | 1545 | 1546 | #### password 1547 | 1548 | The field under validation must match the authenticated user's password. 1549 | 1550 | > **Warning** 1551 | > This rule was renamed to `current_password` with the intention of removing it in Laravel 9. Please use the [Current Password](#rule-current-password) rule instead. 1552 | 1553 | 1554 | #### present 1555 | 1556 | The field under validation must exist in the input data. 1557 | 1558 | 1559 | #### prohibited 1560 | 1561 | The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria: 1562 | 1563 |
1564 | 1565 | - The value is `null`. 1566 | - The value is an empty string. 1567 | - The value is an empty array or empty `Countable` object. 1568 | - The value is an uploaded file with an empty path. 1569 | 1570 |
1571 | 1572 | 1573 | #### prohibited_if:_anotherfield_,_value_,... 1574 | 1575 | The field under validation must be missing or empty if the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria: 1576 | 1577 |
1578 | 1579 | - The value is `null`. 1580 | - The value is an empty string. 1581 | - The value is an empty array or empty `Countable` object. 1582 | - The value is an uploaded file with an empty path. 1583 | 1584 |
1585 | 1586 | If complex conditional prohibition logic is required, you may utilize the `Rule::prohibitedIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be prohibited: 1587 | 1588 | use Illuminate\Support\Facades\Validator; 1589 | use Illuminate\Validation\Rule; 1590 | 1591 | Validator::make($request->all(), [ 1592 | 'role_id' => Rule::prohibitedIf($request->user()->is_admin), 1593 | ]); 1594 | 1595 | Validator::make($request->all(), [ 1596 | 'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin), 1597 | ]); 1598 | 1599 | 1600 | #### prohibited_unless:_anotherfield_,_value_,... 1601 | 1602 | The field under validation must be missing or empty unless the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria: 1603 | 1604 |
1605 | 1606 | - The value is `null`. 1607 | - The value is an empty string. 1608 | - The value is an empty array or empty `Countable` object. 1609 | - The value is an uploaded file with an empty path. 1610 | 1611 |
1612 | 1613 | 1614 | #### prohibits:_anotherfield_,... 1615 | 1616 | If the field under validation is not missing or empty, all fields in _anotherfield_ must be missing or empty. A field is "empty" if it meets one of the following criteria: 1617 | 1618 |
1619 | 1620 | - The value is `null`. 1621 | - The value is an empty string. 1622 | - The value is an empty array or empty `Countable` object. 1623 | - The value is an uploaded file with an empty path. 1624 | 1625 |
1626 | 1627 | 1628 | #### regex:_pattern_ 1629 | 1630 | The field under validation must match the given regular expression. 1631 | 1632 | Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'regex:/^.+@.+$/i'`. 1633 | 1634 | > **Warning** 1635 | > When using the `regex` / `not_regex` patterns, it may be necessary to specify rules in an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. 1636 | 1637 | 1638 | #### required 1639 | 1640 | The field under validation must be present in the input data and not empty. A field is "empty" if it meets one of the following criteria: 1641 | 1642 |
1643 | 1644 | - The value is `null`. 1645 | - The value is an empty string. 1646 | - The value is an empty array or empty `Countable` object. 1647 | - The value is an uploaded file with no path. 1648 | 1649 |
1650 | 1651 | 1652 | #### required_if:_anotherfield_,_value_,... 1653 | 1654 | The field under validation must be present and not empty if the _anotherfield_ field is equal to any _value_. 1655 | 1656 | If you would like to construct a more complex condition for the `required_if` rule, you may use the `Rule::requiredIf` method. This method accepts a boolean or a closure. When passed a closure, the closure should return `true` or `false` to indicate if the field under validation is required: 1657 | 1658 | use Illuminate\Support\Facades\Validator; 1659 | use Illuminate\Validation\Rule; 1660 | 1661 | Validator::make($request->all(), [ 1662 | 'role_id' => Rule::requiredIf($request->user()->is_admin), 1663 | ]); 1664 | 1665 | Validator::make($request->all(), [ 1666 | 'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin), 1667 | ]); 1668 | 1669 | 1670 | #### required_unless:_anotherfield_,_value_,... 1671 | 1672 | The field under validation must be present and not empty unless the _anotherfield_ field is equal to any _value_. This also means _anotherfield_ must be present in the request data unless _value_ is `null`. If _value_ is `null` (`required_unless:name,null`), the field under validation will be required unless the comparison field is `null` or the comparison field is missing from the request data. 1673 | 1674 | 1675 | #### required_with:_foo_,_bar_,... 1676 | 1677 | The field under validation must be present and not empty _only if_ any of the other specified fields are present and not empty. 1678 | 1679 | 1680 | #### required_with_all:_foo_,_bar_,... 1681 | 1682 | The field under validation must be present and not empty _only if_ all of the other specified fields are present and not empty. 1683 | 1684 | 1685 | #### required_without:_foo_,_bar_,... 1686 | 1687 | The field under validation must be present and not empty _only when_ any of the other specified fields are empty or not present. 1688 | 1689 | 1690 | #### required_without_all:_foo_,_bar_,... 1691 | 1692 | The field under validation must be present and not empty _only when_ all of the other specified fields are empty or not present. 1693 | 1694 | 1695 | #### required_array_keys:_foo_,_bar_,... 1696 | 1697 | The field under validation must be an array and must contain at least the specified keys. 1698 | 1699 | 1700 | #### same:_field_ 1701 | 1702 | The given _field_ must match the field under validation. 1703 | 1704 | 1705 | #### size:_value_ 1706 | 1707 | The field under validation must have a size matching the given _value_. For string data, _value_ corresponds to the number of characters. For numeric data, _value_ corresponds to a given integer value (the attribute must also have the `numeric` or `integer` rule). For an array, _size_ corresponds to the `count` of the array. For files, _size_ corresponds to the file size in kilobytes. Let's look at some examples: 1708 | 1709 | // Validate that a string is exactly 12 characters long... 1710 | 'title' => 'size:12'; 1711 | 1712 | // Validate that a provided integer equals 10... 1713 | 'seats' => 'integer|size:10'; 1714 | 1715 | // Validate that an array has exactly 5 elements... 1716 | 'tags' => 'array|size:5'; 1717 | 1718 | // Validate that an uploaded file is exactly 512 kilobytes... 1719 | 'image' => 'file|size:512'; 1720 | 1721 | 1722 | #### starts_with:_foo_,_bar_,... 1723 | 1724 | The field under validation must start with one of the given values. 1725 | 1726 | 1727 | #### string 1728 | 1729 | The field under validation must be a string. If you would like to allow the field to also be `null`, you should assign the `nullable` rule to the field. 1730 | 1731 | 1732 | #### timezone 1733 | 1734 | The field under validation must be a valid timezone identifier according to the `DateTimeZone::listIdentifiers` method. 1735 | 1736 | The arguments [accepted by the `DateTimeZone::listIdentifiers` method](https://www.php.net/manual/en/datetimezone.listidentifiers.php) may also be provided to this validation rule: 1737 | 1738 | 'timezone' => 'required|timezone:all'; 1739 | 1740 | 'timezone' => 'required|timezone:Africa'; 1741 | 1742 | 'timezone' => 'required|timezone:per_country,US'; 1743 | 1744 | 1745 | #### unique:_table_,_column_ 1746 | 1747 | The field under validation must not exist within the given database table. 1748 | 1749 | **Specifying A Custom Table / Column Name:** 1750 | 1751 | Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name: 1752 | 1753 | 'email' => 'unique:App\Models\User,email_address' 1754 | 1755 | The `column` option may be used to specify the field's corresponding database column. If the `column` option is not specified, the name of the field under validation will be used. 1756 | 1757 | 'email' => 'unique:users,email_address' 1758 | 1759 | **Specifying A Custom Database Connection** 1760 | 1761 | Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name: 1762 | 1763 | 'email' => 'unique:connection.users,email_address' 1764 | 1765 | **Forcing A Unique Rule To Ignore A Given ID:** 1766 | 1767 | Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question. 1768 | 1769 | To instruct the validator to ignore the user's ID, we'll use the `Rule` class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the `|` character to delimit the rules: 1770 | 1771 | use Illuminate\Support\Facades\Validator; 1772 | use Illuminate\Validation\Rule; 1773 | 1774 | Validator::make($data, [ 1775 | 'email' => [ 1776 | 'required', 1777 | Rule::unique('users')->ignore($user->id), 1778 | ], 1779 | ]); 1780 | 1781 | > **Warning** 1782 | > You should never pass any user controlled request input into the `ignore` method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack. 1783 | 1784 | Instead of passing the model key's value to the `ignore` method, you may also pass the entire model instance. Laravel will automatically extract the key from the model: 1785 | 1786 | Rule::unique('users')->ignore($user) 1787 | 1788 | If your table uses a primary key column name other than `id`, you may specify the name of the column when calling the `ignore` method: 1789 | 1790 | Rule::unique('users')->ignore($user->id, 'user_id') 1791 | 1792 | By default, the `unique` rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the `unique` method: 1793 | 1794 | Rule::unique('users', 'email_address')->ignore($user->id) 1795 | 1796 | **Adding Additional Where Clauses:** 1797 | 1798 | You may specify additional query conditions by customizing the query using the `where` method. For example, let's add a query condition that scopes the query to only search records that have an `account_id` column value of `1`: 1799 | 1800 | 'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1)) 1801 | 1802 | 1803 | #### uppercase 1804 | 1805 | The field under validation must be uppercase. 1806 | 1807 | 1808 | #### url 1809 | 1810 | The field under validation must be a valid URL. 1811 | 1812 | 1813 | #### ulid 1814 | 1815 | The field under validation must be a valid [Universally Unique Lexicographically Sortable Identifier](https://github.com/ulid/spec) (ULID). 1816 | 1817 | 1818 | #### uuid 1819 | 1820 | The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID). 1821 | 1822 | 1823 | ## Conditionally Adding Rules 1824 | 1825 | 1826 | #### Skipping Validation When Fields Have Certain Values 1827 | 1828 | You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the `exclude_if` validation rule. In this example, the `appointment_date` and `doctor_name` fields will not be validated if the `has_appointment` field has a value of `false`: 1829 | 1830 | use Illuminate\Support\Facades\Validator; 1831 | 1832 | $validator = Validator::make($data, [ 1833 | 'has_appointment' => 'required|boolean', 1834 | 'appointment_date' => 'exclude_if:has_appointment,false|required|date', 1835 | 'doctor_name' => 'exclude_if:has_appointment,false|required|string', 1836 | ]); 1837 | 1838 | Alternatively, you may use the `exclude_unless` rule to not validate a given field unless another field has a given value: 1839 | 1840 | $validator = Validator::make($data, [ 1841 | 'has_appointment' => 'required|boolean', 1842 | 'appointment_date' => 'exclude_unless:has_appointment,true|required|date', 1843 | 'doctor_name' => 'exclude_unless:has_appointment,true|required|string', 1844 | ]); 1845 | 1846 | 1847 | #### Validating When Present 1848 | 1849 | In some situations, you may wish to run validation checks against a field **only** if that field is present in the data being validated. To quickly accomplish this, add the `sometimes` rule to your rule list: 1850 | 1851 | $v = Validator::make($data, [ 1852 | 'email' => 'sometimes|required|email', 1853 | ]); 1854 | 1855 | In the example above, the `email` field will only be validated if it is present in the `$data` array. 1856 | 1857 | > **Note** 1858 | > If you are attempting to validate a field that should always be present but may be empty, check out [this note on optional fields](#a-note-on-optional-fields). 1859 | 1860 | 1861 | #### Complex Conditional Validation 1862 | 1863 | Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a `Validator` instance with your _static rules_ that never change: 1864 | 1865 | use Illuminate\Support\Facades\Validator; 1866 | 1867 | $validator = Validator::make($request->all(), [ 1868 | 'email' => 'required|email', 1869 | 'games' => 'required|numeric', 1870 | ]); 1871 | 1872 | Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the `sometimes` method on the `Validator` instance. 1873 | 1874 | use Illuminate\Support\Fluent; 1875 | 1876 | $validator->sometimes('reason', 'required|max:500', function (Fluent $input) { 1877 | return $input->games >= 100; 1878 | }); 1879 | 1880 | The first argument passed to the `sometimes` method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns `true`, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once: 1881 | 1882 | $validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) { 1883 | return $input->games >= 100; 1884 | }); 1885 | 1886 | > **Note** 1887 | > The `$input` parameter passed to your closure will be an instance of `Illuminate\Support\Fluent` and may be used to access your input and files under validation. 1888 | 1889 | 1890 | #### Complex Conditional Array Validation 1891 | 1892 | Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated: 1893 | 1894 | $input = [ 1895 | 'channels' => [ 1896 | [ 1897 | 'type' => 'email', 1898 | 'address' => 'abigail@example.com', 1899 | ], 1900 | [ 1901 | 'type' => 'url', 1902 | 'address' => 'https://example.com', 1903 | ], 1904 | ], 1905 | ]; 1906 | 1907 | $validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) { 1908 | return $item->type === 'email'; 1909 | }); 1910 | 1911 | $validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) { 1912 | return $item->type !== 'email'; 1913 | }); 1914 | 1915 | Like the `$input` parameter passed to the closure, the `$item` parameter is an instance of `Illuminate\Support\Fluent` when the attribute data is an array; otherwise, it is a string. 1916 | 1917 | 1918 | ## Validating Arrays 1919 | 1920 | As discussed in the [`array` validation rule documentation](#rule-array), the `array` rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail: 1921 | 1922 | use Illuminate\Support\Facades\Validator; 1923 | 1924 | $input = [ 1925 | 'user' => [ 1926 | 'name' => 'Taylor Otwell', 1927 | 'username' => 'taylorotwell', 1928 | 'admin' => true, 1929 | ], 1930 | ]; 1931 | 1932 | Validator::make($input, [ 1933 | 'user' => 'array:name,username', 1934 | ]); 1935 | 1936 | In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's `validate` and `validated` methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules. 1937 | 1938 | 1939 | ### Validating Nested Array Input 1940 | 1941 | Validating nested array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so: 1942 | 1943 | use Illuminate\Support\Facades\Validator; 1944 | 1945 | $validator = Validator::make($request->all(), [ 1946 | 'photos.profile' => 'required|image', 1947 | ]); 1948 | 1949 | You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following: 1950 | 1951 | $validator = Validator::make($request->all(), [ 1952 | 'person.*.email' => 'email|unique:users', 1953 | 'person.*.first_name' => 'required_with:person.*.last_name', 1954 | ]); 1955 | 1956 | Likewise, you may use the `*` character when specifying [custom validation messages in your language files](#custom-messages-for-specific-attributes), making it a breeze to use a single validation message for array based fields: 1957 | 1958 | 'custom' => [ 1959 | 'person.*.email' => [ 1960 | 'unique' => 'Each person must have a unique email address', 1961 | ] 1962 | ], 1963 | 1964 | 1965 | #### Accessing Nested Array Data 1966 | 1967 | Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the `Rule::forEach` method. The `forEach` method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element: 1968 | 1969 | use App\Rules\HasPermission; 1970 | use Illuminate\Support\Facades\Validator; 1971 | use Illuminate\Validation\Rule; 1972 | 1973 | $validator = Validator::make($request->all(), [ 1974 | 'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) { 1975 | return [ 1976 | Rule::exists(Company::class, 'id'), 1977 | new HasPermission('manage-company', $value), 1978 | ]; 1979 | }), 1980 | ]); 1981 | 1982 | 1983 | ### Error Message Indexes & Positions 1984 | 1985 | When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error message displayed by your application. To accomplish this, you may include the `:index` (starts from `0`) and `:position` (starts from `1`) placeholders within your [custom validation message](#manual-customizing-the-error-messages): 1986 | 1987 | use Illuminate\Support\Facades\Validator; 1988 | 1989 | $input = [ 1990 | 'photos' => [ 1991 | [ 1992 | 'name' => 'BeachVacation.jpg', 1993 | 'description' => 'A photo of my beach vacation!', 1994 | ], 1995 | [ 1996 | 'name' => 'GrandCanyon.jpg', 1997 | 'description' => '', 1998 | ], 1999 | ], 2000 | ]; 2001 | 2002 | Validator::validate($input, [ 2003 | 'photos.*.description' => 'required', 2004 | ], [ 2005 | 'photos.*.description.required' => 'Please describe photo #:position.', 2006 | ]); 2007 | 2008 | Given the example above, validation will fail and the user will be presented with the following error of _"Please describe photo #2."_ 2009 | 2010 | 2011 | ## Validating Files 2012 | 2013 | Laravel provides a variety of validation rules that may be used to validate uploaded files, such as `mimes`, `image`, `min`, and `max`. While you are free to specify these rules individually when validating files, Laravel also offers a fluent file validation rule builder that you may find convenient: 2014 | 2015 | use Illuminate\Support\Facades\Validator; 2016 | use Illuminate\Validation\Rules\File; 2017 | 2018 | Validator::validate($input, [ 2019 | 'attachment' => [ 2020 | 'required', 2021 | File::types(['mp3', 'wav']) 2022 | ->min(1024) 2023 | ->max(12 * 1024), 2024 | ], 2025 | ]); 2026 | 2027 | If your application accepts images uploaded by your users, you may use the `File` rule's `image` constructor method to indicate that the uploaded file should be an image. In addition, the `dimensions` rule may be used to limit the dimensions of the image: 2028 | 2029 | use Illuminate\Support\Facades\Validator; 2030 | use Illuminate\Validation\Rule; 2031 | use Illuminate\Validation\Rules\File; 2032 | 2033 | Validator::validate($input, [ 2034 | 'photo' => [ 2035 | 'required', 2036 | File::image() 2037 | ->min(1024) 2038 | ->max(12 * 1024) 2039 | ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)), 2040 | ], 2041 | ]); 2042 | 2043 | > **Note** 2044 | > More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions). 2045 | 2046 | 2047 | #### File Types 2048 | 2049 | Even though you only need to specify the extensions when invoking the `types` method, this method actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location: 2050 | 2051 | [https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) 2052 | 2053 | 2054 | ## Validating Passwords 2055 | 2056 | To ensure that passwords have an adequate level of complexity, you may use Laravel's `Password` rule object: 2057 | 2058 | use Illuminate\Support\Facades\Validator; 2059 | use Illuminate\Validation\Rules\Password; 2060 | 2061 | $validator = Validator::make($request->all(), [ 2062 | 'password' => ['required', 'confirmed', Password::min(8)], 2063 | ]); 2064 | 2065 | The `Password` rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing: 2066 | 2067 | // Require at least 8 characters... 2068 | Password::min(8) 2069 | 2070 | // Require at least one letter... 2071 | Password::min(8)->letters() 2072 | 2073 | // Require at least one uppercase and one lowercase letter... 2074 | Password::min(8)->mixedCase() 2075 | 2076 | // Require at least one number... 2077 | Password::min(8)->numbers() 2078 | 2079 | // Require at least one symbol... 2080 | Password::min(8)->symbols() 2081 | 2082 | In addition, you may ensure that a password has not been compromised in a public password data breach leak using the `uncompromised` method: 2083 | 2084 | Password::min(8)->uncompromised() 2085 | 2086 | Internally, the `Password` rule object uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model to determine if a password has been leaked via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security. 2087 | 2088 | By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the `uncompromised` method: 2089 | 2090 | // Ensure the password appears less than 3 times in the same data leak... 2091 | Password::min(8)->uncompromised(3); 2092 | 2093 | Of course, you may chain all the methods in the examples above: 2094 | 2095 | Password::min(8) 2096 | ->letters() 2097 | ->mixedCase() 2098 | ->numbers() 2099 | ->symbols() 2100 | ->uncompromised() 2101 | 2102 | 2103 | #### Defining Default Password Rules 2104 | 2105 | You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the `Password::defaults` method, which accepts a closure. The closure given to the `defaults` method should return the default configuration of the Password rule. Typically, the `defaults` rule should be called within the `boot` method of one of your application's service providers: 2106 | 2107 | ```php 2108 | use Illuminate\Validation\Rules\Password; 2109 | 2110 | /** 2111 | * Bootstrap any application services. 2112 | */ 2113 | public function boot(): void 2114 | { 2115 | Password::defaults(function () { 2116 | $rule = Password::min(8); 2117 | 2118 | return $this->app->isProduction() 2119 | ? $rule->mixedCase()->uncompromised() 2120 | : $rule; 2121 | }); 2122 | } 2123 | ``` 2124 | 2125 | Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the `defaults` method with no arguments: 2126 | 2127 | 'password' => ['required', Password::defaults()], 2128 | 2129 | Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the `rules` method to accomplish this: 2130 | 2131 | use App\Rules\ZxcvbnRule; 2132 | 2133 | Password::defaults(function () { 2134 | $rule = Password::min(8)->rules([new ZxcvbnRule]); 2135 | 2136 | // ... 2137 | }); 2138 | 2139 | 2140 | ## Custom Validation Rules 2141 | 2142 | 2143 | ### Using Rule Objects 2144 | 2145 | Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the `make:rule` Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the `app/Rules` directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule: 2146 | 2147 | ```shell 2148 | php artisan make:rule Uppercase 2149 | ``` 2150 | 2151 | Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: `validate`. This method receives the attribute name, its value, and a callback that should be invoked on failure with the validation error message: 2152 | 2153 | validate([ 2178 | 'name' => ['required', 'string', new Uppercase], 2179 | ]); 2180 | 2181 | #### Translating Validation Messages 2182 | 2183 | Instead of providing a literal error message to the `$fail` closure, you may also provide a [translation string key](/docs/{{version}}/localization) and instruct Laravel to translate the error message: 2184 | 2185 | if (strtoupper($value) !== $value) { 2186 | $fail('validation.uppercase')->translate(); 2187 | } 2188 | 2189 | If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the `translate` method: 2190 | 2191 | $fail('validation.location')->translate([ 2192 | 'value' => $this->value, 2193 | ], 'fr') 2194 | 2195 | #### Accessing Additional Data 2196 | 2197 | If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the `Illuminate\Contracts\Validation\DataAwareRule` interface. This interface requires your class to define a `setData` method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation: 2198 | 2199 | 2212 | */ 2213 | protected $data = []; 2214 | 2215 | // ... 2216 | 2217 | /** 2218 | * Set the data under validation. 2219 | * 2220 | * @param array $data 2221 | */ 2222 | public function setData(array $data): static 2223 | { 2224 | $this->data = $data; 2225 | 2226 | return $this; 2227 | } 2228 | } 2229 | 2230 | Or, if your validation rule requires access to the validator instance performing the validation, you may implement the `ValidatorAwareRule` interface: 2231 | 2232 | validator = $validator; 2257 | 2258 | return $this; 2259 | } 2260 | } 2261 | 2262 | 2263 | ### Using Closures 2264 | 2265 | If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a `$fail` callback that should be called if validation fails: 2266 | 2267 | use Illuminate\Support\Facades\Validator; 2268 | use Closure; 2269 | 2270 | $validator = Validator::make($request->all(), [ 2271 | 'title' => [ 2272 | 'required', 2273 | 'max:255', 2274 | function (string $attribute, mixed $value, Closure $fail) { 2275 | if ($value === 'foo') { 2276 | $fail("The {$attribute} is invalid."); 2277 | } 2278 | }, 2279 | ], 2280 | ]); 2281 | 2282 | 2283 | ### Implicit Rules 2284 | 2285 | By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the [`unique`](#rule-unique) rule will not be run against an empty string: 2286 | 2287 | use Illuminate\Support\Facades\Validator; 2288 | 2289 | $rules = ['name' => 'unique:users,name']; 2290 | 2291 | $input = ['name' => '']; 2292 | 2293 | Validator::make($input, $rules)->passes(); // true 2294 | 2295 | For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To quickly generate a new implicit rule object, you may use the `make:rule` Artisan command with the `--implicit` option: 2296 | 2297 | ```shell 2298 | php artisan make:rule Uppercase --implicit 2299 | ``` 2300 | 2301 | > **Warning** 2302 | > An "implicit" rule only _implies_ that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you. 2303 | --------------------------------------------------------------------------------