I'm using Laravel 5.1 and its Eloquent model with mysql.
But I would like to populate a collection of models fetching a static array and then querying it as normal. So let's say I have my Photo model and I would query it as usual:
App\Photo::where('published', 1)->get();
But the Photo model should fetch not a DB table but an array like this:
$photos = [
[ "id" => 1, "published" => 1 ],
[ "id" => 2, "published" => 1 ],
[ "id" => 2, "published" => 0 ],
]
My problem is to link this array to that model before querying it. Any ideas?
Don`t know why you want this but if I were you I would put every query method in a service class:
namespace App\Services;
class PhotoService implements PhotoServiceInterface
{
public function getAllPhotos() {
return App\Photo::$photos;
}
//your static array defined in the class as an associative array, you should use **try** **catch** for this or define a default if the key does not exist
public static function getPhotoById($id) {
return App\Photo::$photos[$id];
}
//other functions
public function getAllAlbums() {
return App\Albums::all();
}
}
This way if you want to put them in a table or other changes occur in your app you just have to change this class.
Problem: If you have a model that has a relation to this model you would have to use the service to get it (getPhotoById($user->getPhotoId())
) rather than for ex $user->getPhoto()
. Or you can:
class User
{
....
public function getPhoto() {
return App\Services\PhotoService::getPhotoById($this->photo_id);
}
....
}
Using the lists functionality will return an array of the columns that you specify in the query.
App\Photo::where('published', 1)->lists('id','published');
Hence you can query the model what ever way you want the have it return an array of the fields placed inside lists functionality