Laravel Eloquent Extend Collection Object

Today, We want to share with you Laravel Eloquent Extend Collection Object.In this post we will show you laravel collection to array of objects, hear for Extending the Laravel Eloquent\Collection Class we will give you demo and example for implement.In this post, we will learn about laravel add to collection with an example.

Laravel Eloquent Extend Collection Object

There are the Following The simple About laravel collection select columns Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel collection->filter example, so the laravel custom collection class is used for this example is following below.

Advanced Laravel Eloquent usage

Laravel is a web application framework with expressive, elegant syntax.The PHP Framework for Web Artisans,freeing you to create without sweating the small things. CRUD Operation With Server Side.

$members = Member::all();
if ($members->contains(5))
{
    // A data available with primary key (basically id) 5
}

get a single item

$members = Member::all();
// Print membership_name from first data
echo $members->get(0)->membership_name;
// Print membership_name from third data
echo $members->get(2)->membership_name;

\Illuminate\Database\Eloquent\Collection.php

<?php namespace Extensions;

class CustomCollection extends \Illuminate\Database\Eloquent\Collection {
    public function foo()
    {
        // ...
    }
}

Eloquent Model

class Order extends Eloquent {
    // Override the parent method
    public function newCollection(array $models = Array())
    {
        return new Extensions\CustomCollection($models);
    }
}

app/extensions/customCollection.php

<?php namespace Extensions;

class CustomCollection extends \Illuminate\Database\Eloquent\Collection {

    public function toTable($options = null)
    {
		$header = $atts = '';
		$items = $this->toArray();
		$header_keys = array_keys($items[0]);
		
		if(!is_null($options)) {
			if(array_key_exists('only', $options)) {
				$header_keys = $options['only'];
			}
			if(array_key_exists('attributes', $options)) {
				$attr = $options['attributes'];
			}
		}


		if(is_null($options) || (!isset($options['header']) || isset($options['header']) && $options['header'] != false)) {
			$header = "<thead><tr>";
			foreach ($header_keys as $value) {
				$header .= "<th>" . ucwords(str_replace('_', ' ', $value)) . "</th>";
			}
			$header .= "</tr></thead>";
		}

		$tbody = "<tbody>";
		foreach ($items as $values) {
			$tbody .= "<tr>";
				foreach($header_keys as $key){
					$tbody .= "<td>" . $values[$key] . "</td>";
				}
			$tbody .= "</tr>";
		}
		$tbody .= "</tbody>";

		if(isset($attr)) {
			foreach ($attr as $key => $value) {
				$atts .= " " . $key . "='" . $value . "'";
			}
		}

		if(!is_null($options) && isset($options['table']) && $options['table'] == false) return $tbody;
		
		else return "<table $atts>" . $header . $tbody . "</table>";
	}
}

composer.json

"autoload": {
    "classmap": [
        "app/commands",
        // more...
        "app/extensions"
        ]
    }

Read Also:  PHP Laravel Store Array in Session Examples

<?php
class BaseModel extends Eloquent {
	
	public function newCollection(array $models = Array())
	{
		return new Extensions\CustomCollection($models);
	}
	
}

<?php

use Illuminate\Auth\MemberInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class Member extends BaseModel implements MemberInterface, RemindableInterface {
    // code here
}

// In a controller
$members = Member::all();
$options = array(
    'only' => array('id', 'full_name', 'sir_name', 'membership_name', 'email', 'introduction'),
    'attributes' => array( 'class' => 'table', 'id' => 'tbl1' )
);
return View::make('member.index')
->with('members', $members)
->with('options', $options)

member/index.blade.php

@extends('layouts.master')
@section('content')
    {{ $members->toTable($options) }}
@stop

$options = array(
    'only' => array('id', 'full_name', 'sir_name', 'membership_name', 'email', 'introduction'),
    'attributes' => array( 'class' => 'table table-striped', 'id' => 'tbl1'	),
    'header' => false
);

$options = array(
    'only' => array('id', 'full_name', 'sir_name', 'membership_name', 'email', 'introduction'),
    'attributes' => array( 'class' => 'table table-striped', 'id' => 'tbl1' ),
    'table' => false
);

// Using "table => false" a view could be something like this

@extends('layouts.master')

@section('content')
    <table class="table table-striped">
        <thead>
            <tr>
                <th>ID</th><th>Membername</th><th>Email</th>
            </tr>
        </thead>
        {{ $members->toTable($options) }}
    </table>
@stop

public function odds()
{
    $odd = array();
    foreach ($this->items as $k => $v) {
        if ($k % 2 == 0) $odd[] = $v;
    }
    return new static($odd);    
}


public function evens()
{
    $even = array();
    foreach ($this->items as $k => $v) {
        if ($k % 2 !== 0) $even[] = $v;
    }
    return new static($even);
}

public function getWhere($value, $key)
{
    $index = $this->fetch($key)->toArray();
    $collection = array();
    foreach ($index as $k => $val) {
        if($value == $val) $collection[] = $this->items[$k];
    }
    return count($collection) ? new static($collection) : null;
}

public function __call($method, $args)
{
    $key = snake_case(substr($method, 8));
    $args[] = $key;
    return call_user_func_array(array($this, 'getWhere'), $args);
}

$array = array('name' => 'Modiji', 'email' => '[email protected]');
$new_collection = \Illuminate\Database\Eloquent\Collection::make($array);

$new_collection->toArray();

$new_collection->get('name') // Modiji

$array = array('Modiji', '[email protected]');
$new_collection = \Illuminate\Database\Eloquent\Collection::make($array);

$new_collection->get(1); // [email protected]


$members = Member::all();
$members->find(5);


$new_collection->put(2, 'Male');

$new_collection->shift();

$new_collection->prepend('Married');

$new_collection->push('Married');

$new_collection->pop();

$new_collection->forget(0); // 1st
$new_collection->forget('name');

$members = Member::all();
$members->load('role');
// And more...

Web Programming Tutorials Example with Demo

Read :

Read Also:  PHP Object Oriented Programming Tutorial Example

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel extend model.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  Laravel Convert object Array JSON String Example
  2. Read Also:  Laravel Grouping Cache Offset & Limit Eloquent methods
  3. Read Also:  Laravel UNION Query Builder Example
  4. Read Also:  Laravel Merge Multiple collections Object And Array
  5. Read Also:  Laravel Nested Relationships in Eloquent Example
  6. Read Also:  PHP Laravel Eloquent Data Type Conversion(Casting) Examples
  7. Read Also:  Laravel User Role based Access control Authentication
  8. Read Also:  Laravel 6 Collection Filter Method Examples
  9. Read Also:  how to create One to Many Relationship in laravel?
  10. Read Also:  Merge Multiple Collections in Laravel 6 Eloquent
CLOSEX