We will show you how to insert items element in collections object, this is very simple if you want to add item into last element in collections object with a single method. This short article will give you a quick quide example of Laravel adding items element to the last item collections. Following step by step to use function append Laravel item element in last Laravel collections.
This example you can apply with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.
First we will install Laravel 9 by download via composer. Following command will help you to download project.
composer create-project laravel/laravel blog
Now this step, we will create new controller file and name. You will implment code inside the body signature. Run the command below to create new file TestController.php.
php artisan make:controller AppendController
Open file app -> Http -> Controllers -> AppendController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AppendController extends Controller
{
public function index()
{
$cols = collect(["Dog", "Cat", "Kitty", "Puppy"]);
$cols->push('Parrot');
dd($cols);
}
}
Here, we are going to insert route link into web.php that will point URL to controller and function.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AppendController;
/*
|--------------------------------------------------------------------------
| 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('/', [AppendController::class,'index']);
Using dd()
to print out we didn't need to create view file(blade). Open terminal and type following command to run Laravel server.
php artisan serve
Then launch your browser with URL http://localhost:8000/ to see the collection result.
Illuminate\Support\Collection {#1881 ▼
#items: array:5 [▼
0 => "Dog"
1 => "Cat"
2 => "Kitty"
3 => "Puppy"
4 => "Parrot"
]
}
Hope this article help you to append item in collection Laravel. Have a nice day!
You might also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him