Skip to content

Instantly share code, notes, and snippets.

@zahra-ove
Last active July 12, 2024 12:10
Show Gist options
  • Save zahra-ove/7086eff7e56cfbac8cf5f8e7542002cf to your computer and use it in GitHub Desktop.
Save zahra-ove/7086eff7e56cfbac8cf5f8e7542002cf to your computer and use it in GitHub Desktop.
  1. in blade template engine: {{ $x }} is equal to <?php echo $x ?>
  2. behind the scenes the blade code is compiled to vanilla php.
  3. it is possible to define conditional aggregate in laravel eloquent queries. for example:

suppose we have a table called requested_features which has columns named: title and status.
the status column can has three distinct values: 1.planned 2.requested 3.completed
if we want to count number of records which has "status=planned" and "status=requested" and "status=completed"
then the best solution is:

SELECT
  count(case when status='planned' then 1 end) as planned,
  count(case when status='requested' then 1 end) as requested,
  count(case when status='completed' then 1 end) as completed
FROM features;

and in laravel we can write a query like:

$statuses = Feature::toBase()
                ->selectRaw("count(case when status='planned' then 1 end)")
                ->selectRaw("count(case when status='requested' then 1 end)")
                ->selectRaw("count(case when status='completed' then 1 end)")
                ->first();

  1. using toBase() method on Eloquent model:

In Laravel, Feature::toBase() is a method that converts an Eloquent query builder instance into a plain query builder instance. This is useful when you want to interact with the database using the query builder without the additional Eloquent features.

Understanding toBase()

When you call toBase() on an Eloquent model or query builder, it removes the Eloquent-specific features such as model hydration, relationships, and attribute casting. Essentially, it returns a lower-level query builder that works directly with database rows rather than Eloquent models.

Example Usage

Suppose you have a Feature model and you want to perform a query without the overhead of Eloquent:

use App\Models\Feature;

// Eloquent query builder instance
$query = Feature::where('active', 1);

// Convert to base query builder instance
$baseQuery = $query->toBase();

// Execute the query
$results = $baseQuery->get();

When to Use toBase()

  • Performance Optimization: When you need to optimize performance and don't need Eloquent features.
  • Raw Database Queries: When you need to perform more complex raw database queries that don't fit well with Eloquent's syntax.
  • Complex Joins or Subqueries: When working with complex joins or subqueries that are easier to handle using the base query builder.

Key Points

  • No Model Hydration: The result of toBase()->get() will be a collection of standard PHP objects, not Eloquent models.
  • Direct Database Interaction: Provides a more direct interaction with the database, bypassing Eloquent's additional layers.

Using toBase() can be beneficial when you need more control over your queries and want to avoid the overhead of Eloquent's additional features.


  1. both ->load() and ->with() methods are used for eager loading. but there is a little difference between them:

The primary difference between ->with() and ->load() in Laravel lies in when they are used to load relationships:

  1. ->with(): This method is used when you are building a query and want to eager load relationships at the time of executing the query.
  2. ->load(): This method is used when you already have a model instance (or a collection of model instances) and want to load additional relationships onto those existing instances.

Detailed Comparison

->with()

  • Usage: Use ->with() when you are creating the query to fetch the model(s).
  • Timing: Relationships are loaded as part of the initial query execution.
  • Example:
// In a controller method
public function index() {
    $features = Feature::with('comments', 'comments.users')->get();
    return view('features.index', ['features' => $features]);
}

In this example:

  • The Feature models along with their comments and the users related to those comments are all fetched in a single query (or a few optimized queries).

->load()

  • Usage: Use ->load() when you already have a model instance (or collection) and want to load relationships onto it.
  • Timing: Relationships are loaded after the initial query, using separate queries.
  • Example:
// In a controller method
public function show(Feature $feature) {
    $feature->load('comments.users');
    return view('feature.show', ['feature' => $feature]);
}

In this example:

  • The Feature instance is first retrieved (usually by route model binding).
  • The comments and users relationships are then loaded separately onto the already retrieved Feature instance.

Key Differences

  1. Query Timing:

    • ->with(): Relationships are eager loaded at the time of the initial query.
    • ->load(): Relationships are loaded after the initial query on an existing model instance.
  2. Usage Context:

    • ->with(): Suitable for fetching models with relationships in a single step, often used in query building.
    • ->load(): Suitable for loading relationships on an already retrieved model or collection of models.
  3. Performance:

    • ->with(): Typically more efficient when you know you need the relationships up front, as it minimizes the number of queries.
    • ->load(): Can be used for more complex or conditional relationship loading after the model is retrieved.

Practical Scenarios

Using ->with()

When you need to retrieve a list of features along with their comments and users:

public function index() {
    $features = Feature::with('comments.users')->get();
    return view('features.index', ['features' => $features]);
}

Using ->load()

When you first retrieve a single feature (possibly via route model binding) and then decide to load its comments and users:

public function show(Feature $feature) {
    $feature->load('comments.users');
    return view('feature.show', ['feature' => $feature]);
}

Summary

  • Use ->with() when constructing your query to fetch models along with their relationships in one go.
  • Use ->load() when you need to load relationships onto an already retrieved model instance or collection.

  1. named slot:

In Laravel, the code snippet you provided makes use of Blade components and slots. Here's a breakdown of what x-layout and x-slot:heading mean:

Blade Components

Blade components provide a way to create reusable pieces of code that can be included in multiple views. They help to keep your code DRY (Don't Repeat Yourself) and modular.

x-layout

<x-layout> refers to a Blade component named layout. This component is typically stored in the resources/views/components directory, specifically in a file named layout.blade.php.

x-slot:heading

<x-slot:heading> is a named slot in the layout component. Named slots allow you to define sections of content that can be passed into the component from the parent view. This is useful for inserting specific pieces of content into predefined areas of your component.

Example

Layout Component (resources/views/components/layout.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $heading }}</title>
</head>
<body>
    <header>
        <h1>{{ $heading }}</h1>
    </header>
    <main>
        {{ $slot }}
    </main>
</body>
</html>

In this layout.blade.php file, the {{ $heading }} and {{ $slot }} directives are placeholders for the heading slot and the default slot (the main content), respectively.

Using the Layout Component

<x-layout>
    <x-slot:heading>Job</x-slot:heading>

    <p>title: {{$job['title']}}</p>
    <p>salary: {{$job['salary']}}</p>
</x-layout>

In this example:

  • <x-layout>: Includes the layout component.
  • <x-slot:heading>Job</x-slot:heading>: Passes the value "Job" to the named slot heading.
  • The content inside <x-layout> but outside any named slots (<p>title: {{$job['title']}}</p> and <p>salary: {{$job['salary']}}</p>) is passed to the default slot ({{ $slot }}) in the layout component.

How it Works

  • When the view is rendered, Laravel will include the layout component.
  • It will replace the {{ $heading }} placeholder with the content of the heading slot ("Job").
  • It will replace the {{ $slot }} placeholder with the main content (the two <p> elements).

This approach makes it easy to define a common layout and reuse it with different content in different views. For more detailed information on Blade components and slots, you can refer to the Laravel documentation on Blade components.


  1. what is the difference between: Job::where('id', 5)->delete();

and

Job::findOrFail(5)->delete();

the first one does not retrieve the record from database to application, but the second one does.

  1. Route::view in laravel instead of this code:
Route::get('/contact', function() {
  return  view('contact');
});

we can write this:

Route::view('/contact', 'contact'); 

  1. php artisan route:list --except-vendor
In Laravel, the command php artisan route:list --except-vendor is used to display a list of all the registered routes in your application, excluding routes that are provided by vendor packages. This can be particularly useful when you want to focus on routes defined by your own application code and ignore routes added by third-party packages.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment