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
Related
Working with Laravel 9, I have a state method in my factory defined similar to this:
class PostFactory extends Factory
{
public function definition(): array
{
return [
"user" => User::factory(),
"title" => $this->faker->bs(),
"content" => $this->faker->text(1000),
];
}
public function tagged(): self
{
return $this->state(["tag" => $this->faker->word()]);
}
}
I would like to generate some users who have some tagged posts. But when I try to generate models with this syntax:
$users = User::factory()
->has(Post::factory()->tagged()->count(5), "posts")
->count(5)
->create();
The state method PostFactory::tagged() is only called once (confirmed with debug output in the method) and all 25 posts (5 for each user) have the same tag. I would like each post to have a unique tag. Is there a straightforward way to do this without manually changing them after creation?
I have a laravel table with a column I've defined like this in the migration:
$table->json('json');
And in the model, I cast it to an array:
protected $casts = [
'json' => 'array'
];
This works perfectly the majority of the time I need it, but there's one api call I'm making where I actually want my collection of that Model to give me the raw string rather than casting it to the array.
So, assuming my model is called Model, my api call looks like this:
$systemModels = Model::whereNull('user_id')->get();
$userModels = Model::where('user_id', $user->id)->get();
return response()->json([
'user_models' => $userModels->toArray(),
'system_models' => $systemModels->toArray()
]);
This is where I'd like the 'json' column of my Model to be rendered as a string rather than cast to an array. Is there a reliable way to do that?
Inside your model you can define a custom attribute which is added when the model is serialized:
class YourModel extends Model
{
protected $appends = ['json_raw'];
public function getJsonRawAttribute()
{
return $this->attributes['json'];
// or return json_encode($this->attributes['json']);
}
}
And then when doing the toArray() you can do $userModels->makeHidden('json')->toArray(); to remove the casted field you do not want.
I'm using OctoberCMS based on Laravel and trying to get a list of products within a form via Record Finder.
The use-case is that the record-finder must show available products based on dynamic condition.
I tried to achieve this via "Scope" option of record finder for related form model but not finding a way to pass the dynamic value to the scope.
Sample Code --
class A extends Model
{
public $belongsTo = [
'product' => [
'Plugin\Models\B',
'key' => 'id',
'scope' => 'specificProduct'
],
];
}
class B extends Model
{
public function scopeSpecificProduct($query , $product_type)
{
return $query->where('product_type', $product_type);
}
}
Here $product_type is the dynamic value which I am trying to pass via record finder and get in scope.
Can anyone suggest that is this a correct way for such requirement or how should I achieve this ?
In your fields definition you have to use the scope attribute
fields:
products:
label: Products
type: recordfinder
scope: specificProduct
With this, the second param of your scope will be the A model that is creating or updating
class B extends Model
{
public function scopeSpecificProduct($query , $model)
{
return $query->where('product_type', $model->depend_attribute);
}
}
Hi everyone I am facing problem assigning array(fetched from database) to dropdown list. Here is the Code
Controller Code
$skill_rows = $this->Skill->find("all");
$this->set(compact("skill_rows"));
CTP Code
$skills = $skill_rows;
echo $this->Form->select("Seeker.skills",$skills,array("empty"=>"Select"));
Database
id skill
1 PHP
2 CakePHP
I wish to display only skill column in drop down list but it is displaying complete table.
Use $this->Skill->find("list"); to return an array of primary key-display field values that can be used in your dropdown. You might need to specify skill as the displayField for this to work correctly.
CakePHP 2
In CakePHP 2 the displayField is an attribute of the model:-
class Skill extends AppModel {
public $displayField = 'skill';
}
Alternatively you can define the columns you want to be returned in the list when you perform your find():-
$this->Skill->find('all', [
'fields' => [
'Skill.id',
'Skill.skill'
]
]);
CakePHP 3
In CakePHP 3 you can define the displayField in the model:-
class SkillsTable extends Table
{
public function initialize(array $config)
{
$this->displayField('skill');
}
}
If you want to do this on the find() query in CakePHP 3 you need to define the keyField and valueField:-
$this->Skill->find('list', [
'keyField' => 'id',
'valueField' => 'skill'
]);
When creating an entry using create() - Why does it return a relationship of pilot_id table instead of just showing the value of pilot_id?
For example, in the repository class:
public function createFlight()
$flight = App\Flight::create([
'name' => 'Flight 10'
'pilot_id' => 4
]);
return $flight;
}
In the controller:
public function show()
{
$data = $this->flight->createFlight();
return $data
}
It would return json on the screen but it is not showing the relationship table (pilot) of pilot_id.
Try adding the following to your Flight model, like so. By default you need to tell Laravel to include any relationships.
protected $with = ['pilot'];
That will make it so everytime it includes the relationship. If this is not desirable, then you will want to load the relationships when you return the flight, like so.
return $flight->load(['pilot']);
It shows pilot_id is 4 because that's what its value is. Did you create a relationship on the Flight so that Laravel knows how to retrieve the model for Pilot? It should look something like this:
public function pilot()
{
return $this->hasOne('App\Pilot');
}
When you return a model directly from the controller, it invokes the toJson() method to convert the object to a string. If you want to append the contents of a related model you can do so by adding the relationship to the $with variable on the Flight model.
protected $with = ['pilot']