avatarIsmat Babirli

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5337

Abstract

s-string">'secret'</span>), ]; });</pre></div><p id="1520"><b>5. Route Model Binding</b></p><p id="8397">Route model binding is a feature that allows you to automatically retrieve an instance of a model based on the value of a URL parameter. For example, instead of writing:</p><div id="1ac7" class="link-block"> <a href="https://ismatbabir.medium.com/laravel-routing-how-can-you-use-it-code-example-7a1723ba93e1"> <div> <div> <h2>Laravel Routing: How can you use it? Code example</h2> <div><h3>Laravel routing is an important part of the Laravel web application framework. It lets developers decide how their…</h3></div> <div><p>ismatbabir.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*4sfk6Y6b86RQn3QqLM5Ahw.png)"></div> </div> </div> </a> </div><div id="5a92"><pre><span class="hljs-title class_">Route</span>::<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'users/{id}'</span>, function (<span class="hljs-variable">id</span>) { <span class="hljs-variable">user</span> = <span class="hljs-title class_">App\User</span>::<span class="hljs-title function_ invoke__">find</span>(<span class="hljs-variable">id</span>);</pre></div><div id="bd2e"><pre> <span class="hljs-keyword">return</span> view(<span class="hljs-string">'users.show'</span>, compact(<span class="hljs-string">'user'</span>)); });</pre></div><p id="1407">you can simply write:</p><div id="87dd"><pre><span class="hljs-title class_">Route</span>::<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'users/{user}'</span>, function (App\User <span class="hljs-variable">user</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title function_ invoke__">view</span>(<span class="hljs-string">'users.show'</span>, <span class="hljs-title function_ invoke__">compact</span>(<span class="hljs-string">'user'</span>)); });</pre></div><p id="dd65"><b>6. Task Scheduling with Task Closures</b></p><p id="6859">Task scheduling in Laravel can be done using task closures, which provide a more elegant way of scheduling tasks as compared to scheduling Artisan commands. Task closures can be defined in the <code>app/Console/Kernel.php</code> file, and are executed on a schedule defined in the same file. Here's an example of a task closure:</p><div id="2290"><pre><span class="hljs-variable">schedule</span>-&gt;<span class="hljs-title function_ invoke__">call</span>(function () { <span class="hljs-comment">// Your task logic</span> })-&gt;<span class="hljs-title function_ invoke__">daily</span>();</pre></div><p id="2d1e"><b>7. HTTP middleware</b></p><p id="05ce">HTTP middleware are classes that can be used to filter HTTP requests before they reach your application. For example, you can use a middleware to check if a user is authenticated before allowing them to access a particular route or resource. You can define your own middleware by creating a class in the <code>app/Http/Middleware</code> directory. Here's an example of a simple middleware:</p><div id="9b93" class="link-block"> <a href="https://ismatbabir.medium.com/laravel-middleware-what-is-it-code-examples-74f953e648bb"> <div> <div> <h2>Laravel Middleware: What is it? Code Examples</h2> <div><h3>Laravel Middleware is an important part of the Laravel framework. It lets developers do things before or after an…</h3></div> <div><p>ismatbabir.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Gp7Zpsi4G9VDfZ9t.jpg)"></div> </div> </div> </a> </div><div id="e1a4"><pre><span class="hljs-keyword">namespace</span> App\Http\Middleware;</pre></div><div id="5527"><pre>use Closure<span class="hljs-comment">;</span></pre></div><div id="ff8c"><pre><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CheckAge</span> </span>{ <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params"><span class="hljs-variable">request</span>, <span class="hljs-built_in">Closure</span> <span class="hljs-variable">next</span></span>) </span>{ <span class="hljs-keyword">if</span> (<span class="hljs-variable">request</span>->age <= <span class="hljs-number">200</span>) { <span class="hljs-keyword">return</span> <span class="hljs-variable">next</span>(<span class="hljs-variable">request</span>); }</pre></div><div id="67c1"><pre> <span class="hljs-function"><span class="hljs-keyword">return</span> <span class="hljs-title">redirect</span><span class="hljs-params">(<span class="hljs-string">'home'</span>)</span></span>; } }</pre></div><p id="c3b2"><b>8. Eloquent Subqueries</b></p><p id="e6e6">Eloquent subqueries are a powerful feature that allows you to execute subqueries within an Eloquent query. This can be useful when y

Options

ou need to retrieve data based on the results of another query. Here’s an example of an Eloquent subquery:</p><div id="f557"><pre><span class="hljs-variable">users</span> = <span class="hljs-title class_">App\User</span>::<span class="hljs-title function_ invoke__">select</span>(<span class="hljs-string">'name'</span>) -&gt;<span class="hljs-title function_ invoke__">whereIn</span>(<span class="hljs-string">'id'</span>, function (<span class="hljs-variable">query</span>) { <span class="hljs-variable">query</span>-&gt;<span class="hljs-title function_ invoke__">select</span>(<span class="hljs-string">'user_id'</span>) -&gt;<span class="hljs-keyword">from</span>(<span class="hljs-string">'orders'</span>) -&gt;<span class="hljs-title function_ invoke__">whereRaw</span>(<span class="hljs-string">'orders.created_at &gt;= ?'</span>, [<span class="hljs-title class_">Carbon</span>::<span class="hljs-title function_ invoke__">yesterday</span>()]); }) -&gt;<span class="hljs-title function_ invoke__">get</span>();</pre></div><p id="3b28"><b>9. Route Prefixing</b></p><p id="08e5">Route prefixing allows you to group routes under a common URL prefix. This can be useful when you need to organize your routes into different sections or categories. You can define route prefixes in the <code>routes/web.php</code> or <code>routes/api.php</code> file. Here's an example of how to use route prefixing:</p><div id="f09c"><pre><span class="hljs-title class_">Route</span>::<span class="hljs-title function_ invoke__">prefix</span>(<span class="hljs-string">'admin'</span>)-&gt;<span class="hljs-title function_ invoke__">group</span>(function () { <span class="hljs-title class_">Route</span>::<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'users'</span>, function () { <span class="hljs-comment">// Matches The "/admin/users" URL</span> }); });</pre></div><p id="ad92"><b>10. Query Builder Macros</b></p><p id="a9bd">Query builder macros are custom methods that you can add to the Laravel query builder. This can be useful when you need to reuse a particular query in multiple places throughout your application. You can define query builder macros in the <code>app/Providers/AppServiceProvider.php</code> file. Here's an example of a query builder macro:</p><div id="9dd6"><pre><span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">DB</span>;</pre></div><div id="b7f7"><pre>DB::macro(<span class="hljs-string">'getTotal'</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">table</span>) { <span class="hljs-keyword">return</span> <span class="hljs-symbol">t</span>his-&gt;table(<span class="hljs-symbol">ta</span>ble)-><span class="hljs-built_in">sum</span>(<span class="hljs-string">'total'</span>); });</pre></div><div id="033a"><pre><span class="hljs-comment">// Use the macro</span> $total = DB<span class="hljs-type">::getTotal</span>(<span class="hljs-string">'orders'</span>);</pre></div><p id="315a">Conclusion, Laravel is a powerful and feature-rich framework that has a lot to offer. Whether you’re an experienced Laravel developer or just starting out, there are a few hidden features that you need to know in 2023. We hope that this blog post has helped you discover some new and useful features that will make your Laravel development experience even better.</p><p id="a3cb"><i>Don’t forget to clap at the post and follow me. If you have another option, please share it with us. We would be happy to discuss it with you.</i></p><div id="a7d5" class="link-block"> <a href="https://ismatbabir.medium.com/laravel-10-game-changing-packages-you-cant-afford-to-miss-c44a051b073"> <div> <div> <h2>Laravel: 10 Game-Changing Packages You Can’t Afford to Miss!</h2> <div><h3>Laravel is a powerful and elegant PHP framework, but its true potential is unleashed when you take advantage of the…</h3></div> <div><p>ismatbabir.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*NNAesfgklHeSK7v0)"></div> </div> </div> </a> </div><p id="b88a">If you are not a Medium member, just join from my referral link (to support me, ❤️) and read millions of great articles from Medium.com.</p><div id="6688" class="link-block"> <a href="https://ismatbabir.medium.com/membership"> <div> <div> <h2>Join Medium with my referral link — Ismat Babirli</h2> <div><h3>Register with My Referral Link and Support Me Join Medium with my referral link and get a special welcome package! Not…</h3></div> <div><p>ismatbabir.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Vk3IoMKaSmevnHiT)"></div> </div> </div> </a> </div></article></body>

Laravel Hidden Features You Need to Know in 2024

Photo by Nadine Shaabana on Unsplash

Laravel is a powerful PHP framework that has been around for over a decade. It has gained a massive following due to its elegant syntax, robust set of features, and ease of use. Whether you’re a seasoned Laravel developer or just starting, there are a few hidden features that you might not be aware of. In this blog post, we’ll highlight some of the most useful Laravel hidden features that you need to know in 2023.

  1. Route caching

Route caching is a feature that was introduced in Laravel 5.5. It allows you to cache your application’s routes, which can significantly speed up your application’s boot time. To use route caching, simply run the following command in your terminal:

php artisan route:cache

2. Artisan command scheduler

The Artisan command scheduler allows you to schedule repetitive tasks in your application, such as sending emails, cleaning up old data, or updating your database. To use the Artisan command scheduler, you’ll need to add a task to the app/Console/Kernel.php file:

protected function schedule(Schedule $schedule)
{
    $schedule->command('emails:send')
             ->dailyAt('9:00');
}

3. Automatic Namespace Model Detection

Laravel has a feature called automatic namespace model detection, which allows you to omit the namespace of your models when you are using them. For example, instead of writing:

$user = App\User::find(1);

you can simply write:

$user = User::find(1);

4. Model factories

Model factories are a great way to generate fake data for testing your application. You can define a factory for a model by creating a file in the database/factories directory. For example, here's a factory for a User model:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('secret'),
    ];
});

5. Route Model Binding

Route model binding is a feature that allows you to automatically retrieve an instance of a model based on the value of a URL parameter. For example, instead of writing:

Route::get('users/{id}', function ($id) {
    $user = App\User::find($id);
    return view('users.show', compact('user'));
});

you can simply write:

Route::get('users/{user}', function (App\User $user) {
    return view('users.show', compact('user'));
});

6. Task Scheduling with Task Closures

Task scheduling in Laravel can be done using task closures, which provide a more elegant way of scheduling tasks as compared to scheduling Artisan commands. Task closures can be defined in the app/Console/Kernel.php file, and are executed on a schedule defined in the same file. Here's an example of a task closure:

$schedule->call(function () {
    // Your task logic
})->daily();

7. HTTP middleware

HTTP middleware are classes that can be used to filter HTTP requests before they reach your application. For example, you can use a middleware to check if a user is authenticated before allowing them to access a particular route or resource. You can define your own middleware by creating a class in the app/Http/Middleware directory. Here's an example of a simple middleware:

namespace App\Http\Middleware;
use Closure;
class CheckAge
{
    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return $next($request);
        }
        return redirect('home');
    }
}

8. Eloquent Subqueries

Eloquent subqueries are a powerful feature that allows you to execute subqueries within an Eloquent query. This can be useful when you need to retrieve data based on the results of another query. Here’s an example of an Eloquent subquery:

$users = App\User::select('name')
                 ->whereIn('id', function ($query) {
                     $query->select('user_id')
                           ->from('orders')
                           ->whereRaw('orders.created_at >= ?', [Carbon::yesterday()]);
                 })
                 ->get();

9. Route Prefixing

Route prefixing allows you to group routes under a common URL prefix. This can be useful when you need to organize your routes into different sections or categories. You can define route prefixes in the routes/web.php or routes/api.php file. Here's an example of how to use route prefixing:

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // Matches The "/admin/users" URL
    });
});

10. Query Builder Macros

Query builder macros are custom methods that you can add to the Laravel query builder. This can be useful when you need to reuse a particular query in multiple places throughout your application. You can define query builder macros in the app/Providers/AppServiceProvider.php file. Here's an example of a query builder macro:

use Illuminate\Support\Facades\DB;
DB::macro('getTotal', function ($table) {
    return $this->table($table)->sum('total');
});
// Use the macro
$total = DB::getTotal('orders');

Conclusion, Laravel is a powerful and feature-rich framework that has a lot to offer. Whether you’re an experienced Laravel developer or just starting out, there are a few hidden features that you need to know in 2023. We hope that this blog post has helped you discover some new and useful features that will make your Laravel development experience even better.

Don’t forget to clap at the post and follow me. If you have another option, please share it with us. We would be happy to discuss it with you.

If you are not a Medium member, just join from my referral link (to support me, ❤️) and read millions of great articles from Medium.com.

Laravel
PHP
Programming
Technology
JavaScript
Recommended from ReadMedium