In this post, I will give you an example of the Laravel collection except method. I will explain step-by-step how to use Laravel collection except key and collection except value. Additionally, we will implement an example to demonstrate the Laravel collection except first.
What is Laravel Collection Except Method?
In Laravel, the except method on a collection is used to return all items in the collection except for those with the specified keys. This makes it easy to exclude certain elements from your collection.
Let’s See the Example:
- Example 1: Simple Example of Laravel Collection Except Method
- Example 2: Using Except to Exclude Keys in a Collection
- Example 3: Laravel Collection Except First Value
Syntax:
$collection->except(
$keys_array
)
Laravel collection except method example
Example 1: Simple Example of Laravel Collection Except Method
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index() {
$collection = collect(['id' => 1, 'title' => 'This is main title', "description" => "This is description"]);
$filterdData = $collection->except(['id', 'title']);
dd($filterdData);
}
}
Output:
[
"description" => "This is description"
]
Explanation:
- Input collection: A collection with key like id, title and description.
- except method: Exclude the id and title keys from the collection.
- Output: Returns a collection with only the description.
Example 2: Using Except to Exclude Keys in a Collection
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index() {
$collection = collect(['id' => 1, 'title' => 'This is main title', "description" => "This is description"]);
$excludeKey = ['id', 'title'];
$filterdData = $collection->except($excludeKey);
dd($filterdData);
}
}
Example 3: Laravel Collection Except First Value
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index() {
$collection = collect([10, 20, 30, 40]);
$filterdData = $collection->except(0);
dd($filterdData);
}
}
I hope this tutorial help you.