Laravel Add Items at the End of the Collection
Nov 17, 2022 . Admin
Hello Friends,
In this tutorial, you will learn laravel to add items at the end of the collection. you can understand the concept of how to add values to a collection at the end in laravel. it's a simple example of a laravel collection add items at the end example. We will use laravel to add an element at the end of the collection. So, let's follow a few steps to create an example of a laravel collection and add items at the end.
You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.
You have just to follow the below step and you will get the layout as below:
Step 1: Install LaravelThis is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-appStep 2: Create Format Route web.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AddToEndController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/index',[AddToEndController::class, 'index']);Step 3: create AddToEndController
we will create AddToEndController. so you can see the below code with output:
php artisan make:controller AddToEndControllerApp\Http\Controllers\AddToEndController
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class AddToEndController extends Controller { /** * The attributes that are mass assignable. * * @var array */ public function index() { $collection = new Collection(["Doe", "John", "Gadas", "Maxy"]); $selector = 'Robin'; $collection->push($selector); dd($collection); } }Step 4: Start Development Server
Start the development server. Use the PHP artisan serve command and start your server:
php artisan serve
Now you are ready to run our example so run the below command to quick run.
http://localhost:8000/indexOutput:
#items: array:5 [▼ 0 => "Doe" 1 => "John" 2 => "Gadas" 3 => "Maxy" 4 => "Robin" ]
I hope it can help you...