Creating an arbitrary property in my Model - cakephp

Here's my Model:
class Persona extends AppModel {
// This is just some arbitrary property I need to populate in the controller.
public $TipoPersona = '';
}
And here is the Action function in my Controller:
public function details($id = null) {
// Just a typical load by id.
$this->Persona->id = $id;
$this->set('persona', $this->Persona->read());
// Can I do something like?
$this->Persona->TipoPersona = "Mafa Woogly";
}
How can I set the $TipoPersona property in the "Model" here? My intent is to then use that property in the View like:
<tr>
<th>Tipo de Persona:</th>
<td><?php echo h($persona->TipoPersona); ?></td> // Or similar?
</tr>
Any suggestions?
This works, but feels wonky and not strongly typed.
public function details($id = null) {
$this->Persona->id = $id;
$this->set('persona', $this->Persona->read());
$this->set('tipoPersona', "Mafa woogly");
}
<tr>
<th>Tipo de Persona:</th>
<td><?php echo h($tipoPersona); ?></td>
</tr>

The method read() return an array, you can't get the property TipoPersona of this object.
I recommend you add a field in this table to specify type of person and than use the result of read(), like:
<?php echo $persona['Persona']['tipo_persona']; ?>

Try to add it directly with set:
$this->set('tipoPersona', $this->Persona->TipoPersona);
it's property like everyone else in the model. The same way you are setting $this->Persona->id few lines above :)

You could add it to the result array using Model::afterFind() callback.
Are you sure this shouldn't be a regular field in the Model?

Related

Laravel - Display Array/String Object in view from database

Data are stored as ["item_1", "item_2"] in database like shown below.
I want to display those data in view blade properly.
Product Model
protected $fillable = ['name', 'prod_id'];
public function models() {
return $this->hasMany(Model::class, 'prod_id');
}
Model Model
protected $fillable = ['model', 'prod_id'];
protected $cat = ['model'=>'array'];
public function model()
{
return $this->belongsTo(Product::class, 'prod_id');
}
Controller - store method
public function create (Request $request, Product $product){
$models = new Model;
{
$model = json_encode(request('models'));
$items->models = $model;
$product->models()->save($models);
}
}
Controller show method
public function show(request $id){
$product = Product::findorfail($id);
$models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product', 'models'));
Create View
<input type="checkbox" name="model[]" value="Samsung">
<input type="checkbox" name="model[]" value="Nokia">
<input type="checkbox" name="model[]" value="Apple">
<button>Add Model</button>
I tried show view:
#foreach($models as $model)
{{ json_decode($model->models) }}
#endforeach
It throws
htmlspecialchars() expects parameter 1 to be string, array given
What am I missing.
PS: MySQL does not support json column, so I saved as text column.
you need to do someting like this.
Model Model
protected $fillable = ['models', 'prod_id']; // screenshot says that the field name is "models"
protected $cast = ['models' => 'array']; // the property is $cast no $cat
public function product()
{
return $this->belongsTo(Product::class, 'prod_id');
}
ModelController - store method
public function store (Request $request){
$product = Model::create([
'models' => json_encode($request->models),
'prod_id' => $request->prod_id
]);
return redirect()->back()->with('success', 'created!');
}
public function show(Request $id){
$model = Model::findOrFail($id)->with('product');
return view ('model.show', compact('model'));
}
ProductController show method
public function show(request $id){
$product = Product::findOrFail($id)->with('models'); // the method name is findOrFail() no findorfail
// $models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product'));
}
Into the show View
#foreach($product->models as $models)
#foreach(json_decode($models->models) as $model)
{{ $model }}
#endforeach
#endforeach
Your Models Model confuses me a little bit. You seem to have a field name model that's the same as a relationship method name. That means whenever you include that relation, it'd functionally override that property with data from the related table. (I say 'functionally' because you're using dynamic properties, whereas it is actually possible to explicitly tell Eloquent whether you want an attribute or relation without making it guess.)
That said, your $model->models property could be coming back as an array for one of two reasons. The first is that it may be accidentally referring to a relational data-set and not the JSON string you were expecting. The second is you've corrected the protected $cat = ['model'=>'array']; to read protected $cast = ['models'=>'array'];, and it's stepping on your toes now. By casting it to an array, it may be getting automatically get interpreted back into one before you call json_decode on it.
Either way, I'd dd($model->models) to see what it is first.
You need to change your foreach like this:
#foreach($models->models as $model)
{{ json_decode($model) }}
#endforeach
because Your array is like this
{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}
In here the $models is getting only id and prod_id models is still array so your foreach should be #foreach($models->models as $model)
Sample Code is here:
$arr = '{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}';
echo '<pre>';
foreach (json_decode($arr->models) as $str){
echo $str;
}

Property [id] does not exist on this collection instance when trying to filter the data with 'comment_id'

what i wants to do is to show the replies that are given to that particular comment on the post.Right now i am able to show the comment to that specific post but the replies are displayed along each comment.
here is the controller part of the code:
public function show($id)
{
$blog = Blog::findOrFail($id);
$comments = Comment::where('blog_id', $id)->get()->all();
$test = Comment::all();
// $comments = Comment::whereIn('blog_id', $id)->get()->all();
$commentReplies = CommentReply::where('comment_id'== $test->id)-
>get();
// $commentReplies = CommentReply::where('comment_id',$blog-
>comment()->id)->get()->all();
return
view('admin/blog/front',compact('blog','comments','commentReplies'));
}
i am saving the refrence to that comment in database in 'comment_id' but when i try to reach the 'comment_id' via $commentReplies it gives me the error of "Property [id] does not exist on this collection instance."
The correct syntax is:
$commentReplies = CommentReply::whereIn('comment_id', $test->pluck('id')->toArray())->get();
You also could use relationships. Define this one in the Comment model:
public function replies()
{
return $this->hasMany(CommentReply::class);
}
Then load comments with replies:
$commentsWithReplies = Comment::with('replies')->get();
And to iterate over comments and replies:
#foreach ($commentsWithReplies as $comment)
{{ $comment->text }}
#foreach ($comment->replies as $reply)
{{ $reply->text }}
#endforeach
#endforeach
You also shouldn't chain ->get()->all(), just use ->get().
And finally, the correct syntax for returning a view is (thanks to #Nikola Gavric):
return view('admin.blog.front', compact('blog', 'comments', 'commentReplies'))

CakePHP : Show database view

I have a view in my database and i want to show the value. but i confused how to call the name of view in my controller. i have made a model, but still i can't show the view. my view database’s name is Vtotaleks. Please help me T_T
here my controller
class HomesController extends AppController{
var $uses = array(
'Vtotaleks',
'SiswaMonitoring',
'Siswa',
'AuthUser',
'PerusahaanOrder');
public function index(){
$this->Lib->cekprivilege();
$totalEks = $this->Vtotaleks->find('all', array('cache' => true));
and this my model
<?php
class Vtotaleks extends AppModel
{
public $usetable = 'vtotaleks'; }
and this my view
<tbody>
<?php $totalEkstrainee=0;foreach($totalEks as $datatotalEks){
$totalEkstrainee+=$datatotalEks['Vtotalekstrainee']['siswa_total'];
?>
<tr>
<td><?php echo $datatotalEks['Vtotalekstrainee']['city_name']?></td>
<td align="right"><strong><?php echo $datatotalEks['Vtotalekstrainee']['siswa_total']?></strong></td>
</tr>
<?php }?>
<tr class="danger">
<td><em>Total</em></td>
<td align="right"><strong><?php echo $totalEkstrainee?></strong></td>
</tr>
</tbody>
and here the error
Notice (8): Undefined variable: totalEks [APP\View\Homes\index.ctp, line 142]
Warning (2): Invalid argument supplied for foreach() [APP\View\Homes\index.ctp, line 142]
Add this line after query
$this->set(compact('totalEks'));

How to resolve an undefined value when retrieving data from one controller to another controller's view in cakephp using elements

I am trying to retrieve data from another controller to display it in the PagesController's view using an element. I have a table
service_categories(id, service_category);
my ServiceCategoriesController looks like this
public function category() {
$serviceCategories = $this->paginate();
if ($this->request->is('requested')) {
return $servicesCategories;
} else {
$this->set('serviceCategories', $servicesCategories);
}
}
my category.ctp element looks like this
<?php
$serviceCategories = $this->set('serviceCategories/category');
foreach ($serviceCategories as $serviceCategory):
echo $serviceCategory['ServiceCategory']['service_category'];
endforeach;
But I seem to get an undefined value of "$serviceCategories" when I create an alert before the foreach loop. Please assist! What am I missing?
I rewrite the answer after turning on brain:
In your element replace:
$serviceCategories = $this->set('serviceCategories/category');
with
$serviceCategories = $this->requestAction('service_categories/category');

Cakephp find count group by in view

I have a model Gameline and controller GamelinesController and database 'gamelines'.
I want to run this query
Which means there is one record belongs to 2013-02-18 and there is two records belong to 2013-02-25.
After that how to loop count that belongs to each g_time field in view Please help me.
For fields using MySQL functions, like DATE(). You can use Virtual Fields. In your case, you would add something like this to your Gameline model:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields = array(
'date' => 'DATE(' . $this->alias . '.g_time)'
);
}
That way, the formatted date will be available as the virtual field date (use another name if you already have a field that's called like that).
Then in your find() operation, fetch the new virtual date field. In order to output those results to your view, you can simply loop over your resultset. Let's say you store your find() result in a view parameter called $data, then you would display the table like:
<table>
<thead>
<tr>
<th>Date</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $row): ?>
<tr>
<td><?php echo $row['Gameline']['date']; ?></td>
<td><?php echo $row['Gameline']['count']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

Resources