I have (finally) began working with Laravel after many years mainly developing using CI and was wondering how to ensure all of my returned database rows were returned in the same "format" so to say. For example in Codeigniter I could do the following:
<?php
Class Users_model extends CI_Model
{
public $user_id;
public $name;
public $profile_image;
public $status;
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 0;
const STATUS_DELETED = -1;
function getById($user_id)
{
// typecasting
$user_id = (int) $user_id;
// database query
$this->db->where('id', $user_id);
$q = $this->db->get('users');
// fetch the user record
$row = $result->row();
// set user values
$this->user_id = $row->id;
$this->name = $row->name;
$this->profile_image = $row->image;
$this->status = $row->status;
// return
return $this;
}
function getListOfUsers()
{
// select
$this->db->select('id');
// where query
$this->db->where('status', self::STATUS_ACTIVE);
// exectute query
$q = $this->db->get('users');
// get query results
$results = $q->results();
// set up default return
$return = array();
// loop through db results
foreach($results as $r)
{
$u = new Users_model();
$return[] = $u->getById($r->id);
}
return $return;
}
} ?>
It is a small example but this class would enable me to ensure all of my calls for users from the database run through a singular function (getByID) - obviously everything is heavily cached for performance reasons. What is the best way to apply the same logic in Laravel. Obviously I could write my own model class but it seems silly to use Laravel and not make use of the Eloquent ORM. Any help would be greatly appreciated.
I tried the following:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Products extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'products';
/**
* set the constants
*
*/
const TYPE_USER = 0;
const TYPE_STYLIST = 1;
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
/**
* set the cache constants
*
*/
const CACHE_KEY = 'Product/%d';
const CACHE_LENGTH = 86400;
public $product_id;
public $store;
public $name;
public $slug;
public $url_string;
function getProduct()
{
$this->product_id = (int) 1;
$this->store = (int) 23;
$this->name = (string) 'Nike Air Max';
$this->slug = (string) 'nike-air-max';
$this->url_string = (string) 'http://asos.com';
return $this;
}
} But get all of the unnecessary class information (obviously) and more importantly I don't know how I would apply this using the Eloquent functions such as
$users = User::all();
Thanks for reading
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WIJdyJ
via IFTTT
Aucun commentaire:
Enregistrer un commentaire