File size: 49,276 Bytes
08c8a6d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 |
100 (and counting) Laravel Quick Tips Prepared by: Povilas Korop / LaravelDaily Team www.laraveldaily.com [email protected] Last updated: April 2020 www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: History of changes April 20, 2020: April 28, 2019: November 8, 2018 October 9, 2018 : 10 more tips, total 50 now : Book release with 40 tips 40 more tips, total 100 now (removed duplicated, updated some old ones) 10 more tips, total 60 now Tip 1. Single Action Controllers If you want to create a controller with just one action, you can use even create "invokable" controller. __invoke() method and <?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class ShowProfile extends Controller { /** * Show the profile for the given user. * * @param int $id * @return Response */ public function __invoke($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } } Routes: Route::get('user/{id}', 'ShowProfile'); Artisan command to generate this controller: php artisan make:controller ShowProfile --invokable Tip 2. Unsigned Integer For foreign key migrations instead of integer()->unsigned() , otherwise you may get SQL errors. integer() use unsignedInteger() type or www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: unsignedInteger Schema::create('employees', function (Blueprint $table) { $table-> ('company_id'); $table->foreign('company_id')->references('id')->on('companies'); // ... }); You can also use unsignedBigInteger() if that other column is bigInteger() type. Schema::create('employees', function (Blueprint $table) { $table-> }); unsignedBigInteger ('company_id'); Tip 3. OrderBy on Eloquent relationships You can specify orderBy() directly on your Eloquent relationships. public function products() { return $this->hasMany(Product::class); } public function productsByName() { return $this->hasMany(Product::class)->orderBy('name'); } Tip 4. Order of Migrations If you want to change the order of DB migrations, just rename the file's timestamp, like from 2018_08_04_070443_create_posts_table.php 2018_07_04_070443_create_posts_table.php ). They run in alphabetical order. 2018_07_04 to (changed from to 2018_08_04 www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 5. Raw DB Queries: havingRaw() You can use RAW DB queries in various places, including groupBy() . havingRaw() function after Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get(); Tip 6. $loop variable in foreach Inside of foreach loop, check if current entry is first/last by just using $loop variable. @foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is user {{ $user->id }}</p> @endforeach There are also other properties like More here: https://laravel.com/docs/master/blade#the-loop-variable $loop->iteration or $loop->count . Tip 7. Eloquent where date methods In Eloquent, check the date with functions whereDate() whereTime() and . whereDay() , whereMonth() , whereYear() , $products = Product::whereDate('created_at', '2018-01-31')->get(); $products = Product::whereMonth('created_at', '12')->get(); $products = Product::whereDay('created_at', '31')->get(); $products = Product::whereYear('created_at', date('Y'))->get(); $products = Product::whereTime('created_at', '=', '14:13:58')->get(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 8. Route group within a group in Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the "parent" group. Route::group(['prefix' => 'account', 'as' => 'account.'], function() { Route::get('login', 'AccountController@login'); Route::get('register', 'AccountController@register'); Route::group(['middleware' => 'auth'], function() { Route::get('edit', 'AccountController@edit'); }); }); Tip 9. Increments and decrements if you want to increment some DB column in some table, just use and you can increment not only by 1, but also by some number, like 50. increment() function. Oh, Post::find($post_id)->increment('view_count'); User::find($user_id)->increment('points', 50); Tip 10. Does view file exist? You can check if View file exists before actually loading it. if (view()->exists('custom.page')) { // Load the view } You can even load an array of views and only the first existing will be actually loaded. return view()->first(['custom.dashboard', 'dashboard'], $data); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 11. No timestamp columns If your DB table doesn't contain timestamp fields specify that Eloquent model wouldn't use them, with created_at and $timestamps = false updated_at property. , you can class Company extends Model { public $timestamps = false; } Tip 12. Migration fields with timezones Did you know that in migrations there's not only the timezone? timestamps() but also timestampsTz() , for Schema::create('employees', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email'); $table->timestampsTz(); }); Also, there are columns dateTimeTz() , timeTz() , timestampTz() , softDeletesTz() . Tip 13. Eloquent has() deeper You can use Eloquent has() function to query relationships even two layers deep! // Author -> hasMany(Book::class); // Book -> hasMany(Rating::class); $authors = Author::has(' books.ratings ')->get(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 14. Database migrations column types There are interesting column types for migrations, here are a few examples. $table->geometry('positions'); $table->ipAddress('visitor'); $table->macAddress('device'); $table->point('position'); $table->uuid('id'); See all column types: https://laravel.com/docs/master/migrations#creating-columns Tip 15. Artisan command help To check the options of artisan command, Run artisan commands with example, flag. For and see how many options you have: php artisan make:model --help --help Options: -a, --all Generate a migration, factory, and resource controller for the model -c, --controller Create a new controller for the model -f, --factory Create a new factory for the model --force Create the class even if the model already exists. -m, --migration Create a new migration file for the model. -p, --pivot Indicates if the generated model should be a custom intermediate table model. -r, --resource Indicates if the generated controller should be a resource controller. -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --env[=ENV] The environment the command should run under -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 16. Default Timestamp While creating migrations, you can use ->useCurrent() , it will set CURRENT_TIMESTAMP as default value. ->timestamp() column type with option $table->timestamp('created_at')->useCurrent(); $table->timestamp('updated_at')->useCurrent(); Tip 17. Set logged in user with Observers Use make:observer current logged in user. and fill in creating() method to automatically set up user_id field for class PostObserver { /** * Handle to the post "creating" event. * * @param \App\Post $post * @return void */ public function creating(Post $post) { $post->user_id = auth()->id(); } } Tip 18. Soft-deletes: multiple restore When using soft-deletes, you can restore multiple rows in one sentence. Post::withTrashed()->where('author_id', 1)->restore(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 19. Has Many. How many exactly? In Eloquent records. hasMany() relationships, you can filter out records that have X amount of children // Author -> hasMany(Book::class) $authors = Author::has('books', '>', 5)->get(); Tip 20. Image validation While validating uploaded images, you can specify the dimensions you require. 'photo' => 'dimensions:max_width=4096,max_height=4096' Tip 21. Wildcard subdomains You can create route group by dynamic subdomain name, and pass its value to every route. {username} Route::domain(' Route::get('user/{id}', function ( // }); }); .workspace.com')->group(function () { $username , $id) { Tip 22. Exact Laravel version Find out exactly what Laravel version you have in your app, by running command php artisan --version www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 23. Testing email into laravel.log If you want to test email contents in your app but unable or unwilling to set up something like Mailgun, use .env storage/logs/laravel.log and all the email will be saved into file, instead of actually being sent. MAIL_DRIVER=log parameter Tip 24. Error code Blade pages If you want to create a specific error page for some HTTP code, like 500 - just create a blade file with this code as filename, in 403.blade.php , or etc, and it will automatically be loaded in case of that error code. resources/views/errors/500.blade.php Tip 25. Factory callbacks While using factories for seeding data, you can provide Factory Callback functions to perform some action after record is inserted. $factory->afterCreating(App\User::class, function ($user, $faker) { $user->accounts()->save(factory(App\Account::class)->make()); }); Tip 26. Artisan command parameters When creating Artisan command, you can ask the input in variety of ways: $this->choice() $this->anticipate() . , $this->confirm() , // Yes or no? if ($this->confirm('Do you wish to continue?')) { // } // Open question with auto-complete options $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); // One of the listed options with default index $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 27. Preview Mailables If you use Mailables to send email, you can preview the result without sending, directly in your browser. Just return a Mailable as route result: Route::get('/mailable', function () { $invoice = App\Invoice::find(1); return new App\Mail\InvoicePaid($invoice); }); Tip 28. Route::view() - Don't create Controllers If you want route to just show a certain view, don't create a Controller method, just use Route::view() function. // Instead of this Route::get('about', 'TextsController@about'); // And this class TextsController extends Controller { public function about() { return view('texts.about'); } } // Do this Route::view('about', 'texts.about'); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 29. Blade @auth Instead of if-statement to check logged in user, use @auth directive. Typical way: @if(auth()->user()) // The user is authenticated. @endif Shorter: @auth // The user is authenticated. @endauth The opposite is @guest directive. @guest // The user is not authenticated. @endguest Tip 30. Model all: columns When calling Eloquent's Model::all() , you can specify which columns to return. $users = User::all(['id', 'name', 'email']); Tip 31. Localhost in .env Don't forget to change in your it will be the basis for any links in your email notifications and elsewhere. http://localhost APP_URL file from .env to real URL, cause APP_NAME=Laravel APP_ENV=local APP_KEY=base64:9PHz3TL5C4YrdV6Gg/Xkkmx9btaE93j7rQTUZWm2MqU= APP_DEBUG=true APP_URL= http://localhost www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 32: What's behind the routes? Want to know what routes are actually behind From Laravel 7, it’s in a separate package, so check the file . /vendor/laravel/ui/src/AuthRouteMethods.php Auth::routes() ? public function auth() { return function ($options = []) { // Authentication Routes... $this->get('login', 'Auth\LoginController@showLoginForm')->name('login'); $this->post('login', 'Auth\LoginController@login'); $this->post('logout', 'Auth\LoginController@logout')->name('logout'); // Registration Routes... if ($options['register'] ?? true) { $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); $this->post('register', 'Auth\RegisterController@register'); } // Password Reset Routes... if ($options['reset'] ?? true) { $this->resetPassword(); } // Password Confirmation Routes... if ($options['confirm'] ?? class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) { $this->confirmPassword(); } // Email Verification Routes... if ($options['verify'] ?? false) { $this->emailVerification(); } }; } Before Laravel 7, check the file /vendor/laravel/framework/src/illuminate/Routing/Router.php . public function auth(array $options = []) { // Authentication Routes... $this->get('login', 'Auth\LoginController@showLoginForm')->name('login'); $this->post('login', 'Auth\LoginController@login'); $this->post('logout', 'Auth\LoginController@logout')->name('logout'); // Registration Routes... www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: if ($options['register'] ?? true) { $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); $this->post('register', 'Auth\RegisterController@register'); } // Password Reset Routes... $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request'); $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email'); $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset'); $this->post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update'); // Email Verification Routes... if ($options['verify'] ?? false) { $this->emailVerification(); } } public function emailVerification() { $this->get('email/verify', 'Auth\VerificationController@show')->name('verification.notice'); $this->get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); $this->get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend'); } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 33. To Fail or not to Fail In addition to findOrFail() 404 page if no records for query are found. , there's also Eloquent method firstOrFail() which will return $user = User::where('email', '[email protected]')->firstOrFail(); Tip 34. Column name change in Eloquent Query Builder, you can specify "as" to return any column with a different name, just like in plain SQL query. $users = DB::table('users') ->select('name', 'email as user_email') ->get(); Tip 35. Logging with parameters You can write context about what happened. Log::info() , or shorter info() message with additional parameters, for more Log::info('User failed to login.', ['id' => $user->id]); Tip 36. Default Model You can assign a default model in like {{ $post->user->name }} belongsTo if $post->user doesn't exist. relationship, to avoid fatal errors when calling it /** * Get the author of the post. */ public function user() { return $this->belongsTo('App\User')->withDefault(); } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 37. Use hasMany to create Many If you have from your "parent" object, all in one sentence. relationship, you can use hasMany() saveMany() to save multiple "child" entries $post = Post::find(1); $post->comments()->saveMany([ new Comment(['message' => 'First comment']), new Comment(['message' => 'Second comment']), ]); Tip 38. More convenient DD Instead of doing Eloquent sentence, or any Collection. dd($result); you can put ->dd() as a method directly at the end of your // Instead of $users = User::where('name', 'Taylor')->get(); dd($users); // Do this $users = User::where('name', 'Taylor')->get()->dd(); Tip 39. Map query results After Eloquent query you can modify rows by using map() function in Collections. $users = User::where('role_id', 1)->get()->map(function (User $user) { $user->some_column = some_function($user); return $user; }); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 40. Custom validation error messages You can customize validation error messages per specific language file structure. and resources/lang/xx/validation.php field rule , language with appropriate array - just create a 'custom' => [ 'email' => [ 'required' => 'We need to know your e-mail address!', ], ], Tip 41. When (NOT) to run “composer update” Not so much about Laravel, but... Never run "break" repository. Always run composer.lock to the repository, and run composer update composer update on production, it's slow and will locally on your computer, commit new on server. composer install Tip 42. Two-level $loop variable in Blade In Blade's foreach you can use $loop variable even in two-level loop to reach parent variable. @foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is first iteration of the parent loop. @endif @endforeach @endforeach www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 43. Route Model Binding: You can define a key You can do Route model binding like (App\User $user) { … } field, put this in the model: Route::get('api/users/{user}', function - but not only by ID field. If you want {user} to be a username public function getRouteKeyName() { return 'username'; } Tip 44. Redirect to Specific Controller Method You can method, and even pass the parameters. Use this: redirect() not only to URL or specific route, but to a specific Controller's specific return redirect()->action('SomeController@method', ['param' => $value]); Tip 45. Did you know about Auth::once()? You can login with user only for ONE REQUEST, using method cookies will be utilized, which means this method may be helpful when building a stateless API. Auth::once() . No sessions or if (Auth::once($credentials)) { // } Tip 46. Eager Loading with Exact Columns You can do Laravel Eager Loading and specify the exact columns you want to get from the relationship. $users = App\Book::with('author:id,name')->get(); You can do that even in deeper, second level relationships: $users = App\Book::with('author.country:id,name')->get(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 47. Validate dates with "now" or "yesterday" words You can validate dates by rules before/after and passing various strings as a parameter, like: "tomorrow", "now", "yesterday". Example: strtotime() under the hood. 'start_date' => 'after:now' . It's using $rules = [ 'start_date' => 'after:tomorrow', 'end_date' => 'after:start_date' ]; Tip 48. Touch parent updated_at easily If you are updating a record and want to update the (like, you add new post comment and want = ['post']; property on child model. updated_at posts.updated_at column of parent relationship to renew), just use $touches class Comment extends Model { /** * All of the relationships to be touched. * * @var array */ protected $touches = ['post']; } Tip 49. Quickly Navigate from Routes file to Controller Instead of routing like this: Route::get('page', 'PageController@action'); You can specify the Controller as a class: Route::get('page', [\App\Http\Controllers\PageController::class, 'action']); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Then you will be able to click on “PageController” in PhpStorm, and navigate directly to Controller, instead of searching for it manually. Tip 50. Always Check if Relationship Exists Never ever do $model->relationship->field object still exists. without checking if relationship It may be deleted for whatever reason, outside your code, by someone else's queued job etc. Do if-else Blade, or {{ optional($model->relationship)->field }} , or {{ $model->relationship->field ?? '' }} in Tip 51. Don’t Filter by NULL in Collections You can filter by NULL in Eloquent, but if you're filtering the collection further - filter by empty string, there's no "null" in that field anymore. // This works $messages = Message::where( ' read_at is null ' )->get(); // Won’t work - will return 0 messages $messages = Message::all(); $unread_messages = $messages->where( ' read_at is null ' )->count(); // Will work $unread_messages = $messages->where( ' read_at ' , '' )->count(); Tip 52. Default Email Subject in Laravel Notifications If you send Laravel Notification and don't specify subject in toMail(), default subject is your notification class name, CamelCased into Spaces. So, if you have: class UserRegistrationEmail extends Notification { // ... Then you will receive an email with subject “User Registration Email”. www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 53. Composer: Check for Newer Versions If you want to find out which of your composer.json packages have released newer versions, just run "composer outdated". You will get a full list with all information, like this below. phpdocumentor/type-resolver 0.4.0 0.7.1 phpunit/php-code-coverage 6.1.4 7.0.3 Library that provides collection, processing, and rende... phpunit/phpunit 7.5.9 8.1.3 The PHP Unit Testing framework. ralouphie/getallheaders 2.0.5 3.0.3 A polyfill for getallheaders. sebastian/global-state 2.0.0 3.0.0 Snapshotting of global state Tip 54. Route Fallback - When no Other Route is Matched If you want to specify additional logic for not-found routes, instead of just throwing default 404 page, you may create a special Route for that, at the very end of your Routes file. Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () { Route::get('/home', 'HomeController@index'); Route::resource('tasks', 'Admin\TasksController'); }); // Some more routes.... Route::fallback(function() { return 'Hm, why did you land here somehow?'; }); Tip 55. Create Your Own Blade Directive It’s very easy - just add your own method in app/Providers/AppServiceProvider.php: For example, if you want to have this for replace <br> tags with new lines: <textarea>@br2nl($post->post_text)</textarea> www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Add this directive to AppServiceProvider’s boot() method: public function boot() { Blade::directive('br2nl', function ($string) { return "<?php echo preg_replace('/\<br(\s*)?\/?\>/i', \"\n\", $string); ?>"; }); } Tip 56. Use withCount() to Calculate Child Relationships Records If you have hasMany() relationship, and you want to calculate “children” entries, don’t write a special query. For example, if you have posts and comments on your User model, write this withCount(): public function index() { $users = User::withCount(['posts', 'comments'])->get(); return view('users', compact('users')); } And then, in your Blade file, you will access those number with [relationship]_count properties: @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td class="text-center">{{ $user->posts_count }}</td> <td class="text-center">{{ $user->comments_count }}</td> </tr> @endforeach Tip 57. Use groupBy on Collections with Custom Callback Function If you want to group result by some condition whith isn’t a direct column in your database, you can do that by providing a closure function. www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: For example, if you want to group users by day of registration, here’s the code: $users = User::all()->groupBy(function($item) { return $item->created_at->format('Y-m-d'); }); Notice: it is done on a Collection class, so performed AFTER the results are fetched from the database. Tip 58. Blade Directives: IncludeIf, IncludeWhen, IncludeFirst If you are not sure whether your Blade partial file actually would exist, you may use these condition commands: This will load header only if Blade file exists @includeIf('partials.header') This will load header only for user with role_id 1 @includeWhen(auth()->user()->role_id == 1, 'partials.header') This will try to load adminlte.header, if missing - will load default.header @includeFirst('adminlte.header', 'default.header') Tip 59. Change Default Timestamp Fields What if you’re working with non-Laravel database and your timestamp columns are named differently? Maybe, you have create_time and update_time. Luckily, you can specify them in the model, too: class Role extends Model { const CREATED_AT = 'create_time'; const UPDATED_AT = 'update_time'; www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 60. Quick Order by created_at Instead of: User::orderBy('created_at', 'desc')->get(); You can do it quicker: User::latest()->get(); By default, latest() will order by created_at . There is an opposite method oldest() User::oldest()->get(); which would order by created_at ascending. Also, you can specify another column to order by. For example, if you want to use updated_at $lastUpdatedUser = User::newest('updated_at')->first(); , you can do this: Tip 61. Generate Images with Seeds/Factories Did you know that Faker can generate not only text values but also IMAGES? See avatar field here - it will generate 50x50 image: $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => bcrypt('password'), 'remember_token' => Str::random(10), 'avatar' => $faker->image(storage_path('images'), 50, 50) ]; }); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 62. Eloquent: Update Parent in One Line If you have a belongsTo() data in the same sentence: relationship, you can update the Eloquent relationship // if Project -> belongsTo(User::class) $project->user->update(['email' => '[email protected]']); Tip 63. Eloquent: Laravel 7+ Foreign Keys From Laravel 7, in migrations you don't need to write two lines for relationship field - one for the field and one for foreign key. Use method foreignId() . // Before Laravel 7 Schema::table('posts', function (Blueprint $table)) { $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users'); } // From Laravel 7 Schema::table('posts', function (Blueprint $table)) { $table->foreignId('user_id')->constrained(); } // Or, if your field is different from the table reference Schema::table('posts', function (Blueprint $table)) { $table->foreignId('created_by_id')->references('id')->on('users'); } Tip 64. Multiple Collection Methods in a Row If you query all results with ->all() or ->get(), you may then perform various Collection operations on the same result, it won’t query database every time. $users = User::all(); echo 'Max ID: ' . $users->max('id'); echo 'Average age: ' . $users->avg('age'); echo 'Total budget: ' . $users->sum('budget'); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 65. More Events on User Registration Want to perform some actions after new user registration? Head to app/Providers/EventServiceProvider.php and then in those classes implement handle() and add more Listeners classes, method with $event->user object class EventServiceProvider extends ServiceProvider { protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, // You can add any Listener class here // With handle() method inside of that class ], ]; Tip 66. Extra Filter Query on Relationships If you want to load relationship data, you can specify some limitations or ordering in a closure function. For example, if you want to get Countries with only three of their biggest cities, here's the code. $countries = Country::with(['cities' => function($query) { $query->orderBy('population', 'desc'); $query->take(3); }])->get(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 67. Send Notifications to Anyone You can send Laravel Notifications not only to a certain user with $user->notify() so-called "on-demand" notifications: , but also to anyone you want, via Notification::route() , with Notification::route('mail', '[email protected]') ->route('nexmo', '5555555555') ->route('slack', 'https://hooks.slack.com/services/...') ->notify(new InvoicePaid($invoice)); Tip 68. Sub-selects in Laravel Way From Laravel 6, you can use addSelect() calculation to that added column. in Eloquent statement, and do some return Destination::addSelect(['last_flight' => Flight::select('name') ->whereColumn('destination_id', 'destinations.id') ->orderBy('arrived_at', 'desc') ->limit(1) ])->get(); Tip 69. API Resources: With or Without “data”? If you use Eloquent API Resources to return data, they will be automatically wrapped in 'data'. If you want to remove it, add JsonResource::withoutWrapping(); app/Providers/AppServiceProvider.php in . class AppServiceProvider extends ServiceProvider { public function boot() { JsonResource::withoutWrapping(); } } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 70. API Return “Everything went ok” If you have API endpoint which performs some operations but has no response, so you wanna return just "everything went ok", you may return 204 status code "No content": https://httpstatuses.com/204 In Laravel, it's easy: return response()->noContent(); public function reorder(Request $request) { foreach ($request->input('rows', []) as $row) { Country::find($row['id'])->update([ 'position' => $row['position']; ]); } return response()->noContent(); } Tip 71. Automatic Column Value When Creating Records If you want to generate some DB column value when creating record, add it to model's boot() For example, if you have a field "position" and want to assign the next available position to the new record (like Country::max('position') + 1 method. ), do this. class Country extends Model { // ... protected static function boot() { parent::boot(); // every new record will get next available position number Country::creating(function($model) { $model->position = Country::max('position') + 1; }); } } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 72. DB Raw Query Calculations Run Faster Use SQL raw queries like whereRaw() calculations directly in query, and not in Laravel, usually the result will be faster. Like, if you want to get users that were active 30+ days after their registration, here's the code. method, to make some DB-specific User::where('active', 1) ->whereRaw('TIMESTAMPDIFF(DAY, created_at, updated_at) > ?', 30) ->get(); Tip 73. More than One Scope You can combine and chain Query Scopes in Eloquent, using more than one scope in a query. // app/User.php model public function scopeActive($query) { return $query->where('active', 1); } public function scopeRegisteredWithinDays($query, $days) { return $query->where('created_at', '>=', now()->subDays($days)); } // Some Controller $users = User::registeredWithinDays(30)->active()->get(); Tip 74. Hide Some Columns When doing Eloquent query, if you want to hide specific field from being returned, one of the quickest ways is to add ->makeHidden() on Collection result. $users = User::all()->makeHidden(['email_verified_at', 'deleted_at']); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 75. Combine Two “whereHas” In Eloquent, you can combine whereHas() and orDoesntHave() in one sentence. User::whereHas('roles', function($query) { $query->where('id', 1); }) ->orDoesntHave('roles') ->get(); Tip 76. Auto-Capitalize Translations In translation files (resources/lang :variable value you pass - will be also capitalized automatically. , but also capitalized as :VARIABLE ), you can specify variables not only as or :Variable - and then whatever // resources/lang/en/messages.php 'welcome' => 'Welcome, :Name' // Result: "Welcome, Taylor" echo __('messages.welcome', ['name' => 'taylor']); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 77. Validation Rule with Some Conditions If your validation rules depend on some condition, you can modify the rules by adding withValidator() to your FormRequest logic there. Like, if you want to add validation rule only for some user role. class, and specify your custom use Illuminate\Validation\Validator; class StoreBlogCategoryRequest extends FormRequest { // ... public function withValidator(Validator $validator) { if (auth()->user()->is_admin) { $validator->addRules([ 'some_secret_password' => 'required' ]); } } } Tip 78. Check if Relationship Method Exists If your Eloquent relationship names are dynamic and you need to check if relationship with such name exists on the object, use PHP function method_exists($object, $methodName) $user = User::first(); if (method_exists($user, 'roles')) { // Do something with $user->roles()->... } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 79. Exact DB Error If you want to catch Eloquent Query exceptions, use specific QueryException instead default Exception class, and you will be able to get the exact SQL code of the error. try { // Some Eloquent/SQL statement } catch (\Illuminate\Database\QueryException $e) { if ($e->getCode() === '23000') { // integrity constraint violation return back()->withError('Invalid data'); } } Tip 80. Route Parameters Validation with RegExp We can validate parameters directly in the route, with “where” parameter. A pretty typical case is to prefix your routes by language locale, like fr/blog and en/article/333. How do we ensure that those two first letters are not used for some other than language? // routes/web.php Route::group([ 'prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}'] ], function () { Route::get('/', 'HomeController@index'); Route::get('article/{id}', 'ArticleController@show'); }); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 81. Rate Limiting: Global and for Guests/Users You can limit some URL to be called a maximum of 60 times per minute, with throttle:60,1 . Route::middleware('auth:api', 'throttle:60,1')->group(function () { Route::get('/user', function () { // }); }); But also, you can do it separately for public and for logged-in users. // maximum of 10 requests for guests, 60 for authenticated users Route::middleware('throttle:10|60,1')->group(function () { // }); Also, you can have a DB field users.rate_limit and limit the amount for specific user: Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () { Route::get('/user', function () { // }); }); Tip 82. Add Parameters to Routes If you pass additional parameters to the route, in the array, those key / value pairs will automatically be added to the generated URL's query string. Route::get('user/{id}/profile', function ($id) { // })->name('profile'); $url = route('profile', ['id' => 1, 'photos' => 'yes']); // Result: /user/1/profile?photos=yes www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 83. Check Multiple Permissions at Once In addition to @can at once with @canany directive? Blade directive, did you know you can check multiple permissions @canany(['update', 'view', 'delete'], $post) // The current user can update, view, or delete the post @elsecanany(['create'], \App\Post::class) // The current user can create a post @endcanany Tip 84. Check Auth Quicker If, in Blade, you need to check if user is logged in, don't do @if (auth()->check()) - there is a shorter way: directives @auth - @endauth and @guest - @endguest @auth // The user is authenticated... @endauth @guest // The user is not authenticated... @endguest Tip 85. No Need to Convert Carbon If you're performing whereDate() now() and it will automatically be transformed to date. No need to do and check today's records, you can use Carbon's ->toDateString() . // Instead of $todayUsers = User::whereDate('created_at', now()->toDateString())->get(); // No need to convert, just use now() $todayUsers = User::whereDate('created_at', now())->get(); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 86. Soft-Deletes with Query Builder Don't forget that soft-deletes will exclude entries when you use Eloquent, but won't work if you use Query Builder. // Will exclude soft-deleted entries $users = User::all(); // Will NOT exclude soft-deleted entries $users = DB::table('users')->get(); Tip 87. Grouping by First Letter You can group Eloquent results by any custom condition, here's how to group by first letter of user's name. $users = User::all()->groupBy(function($item) { return $item->name[0]; }) Tip 88. Load Relationships Always, but Dynamically You can not only specify what relationships to ALWAYS load with the model, but you can do it dynamically, in the constructor method: class ProductTag extends Model { protected $with = ['product']; public function __construct() { parent::__construct(); $this->with = ['product']; if (auth()->check()) { $this->with[] = 'user'; } } } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 89. Instead of belongsTo, use hasMany For belongsTo record, use hasMany relationship, instead of passing parent's ID when creating child relationship to make a shorter sentence. // if Post -> belongsTo(User), and User -> hasMany(Post)... // Then instead of passing user_id... Post::create([ 'user_id' => auth()->id(), 'title' => request()->input('title'), 'post_text' => request()->input('post_text'), ]); // Do this auth()->user()->posts()->create([ 'title' => request()->input('title'), 'post_text' => request()->input('post_text'), ]); Tip 90. Change Default Validation Messages If you want to change default validation error message for specific field and specific validation rule, just add a messages() method into your FormRequest class. class StoreUserRequest extends FormRequest { public function rules() { return ['name' => 'required’]; } public function messages() { return [ 'name.required' => 'User name should be real name', ]; } } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 91. Validate Images Dimensions In validation, you can check uploaded images dimensions, specifying rules for min/max witdh/height, and even ratio. 'avatar' => 'dimensions:min_width=100,min_height=200,dimensions:3/2' Tip 92. Carbon with Only Hours/Minutes if you want to have a current date without seconds and/or minutes, use Carbon's methods like setSeconds(0) or setMinutes(0). // 2020-04-20 08:12:34 echo now(); // 2020-04-20 08:12:00 echo now()->setSeconds(0); // 2020-04-20 08:00:00 echo now()->setSeconds(0)->setMinutes(0); // Another way - even shorter echo now()->startOfHour(); Tip 93. Good Old SQL Query If you need to execute a simple SQL query, without getting any results - like changing something in DB schema, you can just do DB::statement() . DB::statement('DROP TABLE users'); DB::statement('ALTER TABLE projects AUTO_INCREMENT=123'); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 94. Prepare for Validation If you want to modify some field before default Laravel validation, or, in other words, "prepare" that field, guess what - there's a method prepareForValidation() FormRequest class: in protected function prepareForValidation() { $this->merge([ 'slug' => Illuminate\Support\Str::slug($this->slug), ]); } Tip 95. Rename Pivot Table If you want to rename "pivot" word and call your relationship something else, you just use as('name') in your relationship: public function podcasts() { return $this->belongsToMany('App\Podcast') ->as('subscription') ->withTimestamps(); } // Then somewhere in Controller... $podcasts = $user->podcasts(); foreach ($podcasts as $podcast) { // instead of $podcast->pivot->created_at ... echo $podcast->subscription->created_at; } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 96. Similar Relationship but With Condition If you notice that you use same relationship often with additional "where" condition, you can create a separate relationship method. // app/Post.php model public function comments() { return $this->hasMany(Comment::class); } public function approved_comments() { return $this->hasMany(Comment::class)->where('approved', 1); } Tip 97. Never Update the Column If you have DB column which you want to be set only once and never updated again, you can set that restriction on Eloquent Model, with a mutator: class User extends Model { public function setEmailAttribute($value) { if ($this->email) { return; } $this->attributes['email'] = $value; } } www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 98. Maintenance Mode If you want to enable maintenance mode on your page, execute the down Artisan command: php artisan down Then people would see default 503 status page. You may also provide flags: - message that would be shown - retry page reload every X seconds - still allow the access to some IP address php artisan down --message="Upgrading Database" --retry=60 --allow=127.0.0.1 When you've done the maintenance work, just run php artisan up Tip 99. Find Many Eloquent method find() may accept multiple parameters, and then it returns a Collection of all records found, not just one Model. // Will return Eloquent Model $user = User::find(1); // Will return Eloquent Collection $users = User::find([1,2,3]); www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: Tip 100. Stop on First Validation Error By default, Laravel validation errors will be returned in a list, checking all validation rules. But if you want the process to stop after the first error, use validation rule called bail : $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]); To be continued… Follow @DailyLaravel on Twitter for updates Or subscribe to our weekly newsletter: http://bit.ly/laravel-newsletter www.quickadminpanel.com Support our work by checking our Laravel adminpanel generator: |