October Database - database

I have this code
public function onRequest(){
$users = \Db::table('engegraph_forms_membros')->get();
foreach ($users as $part) {
echo $part->membro; // membro ITS NAME FROM ONE COLUMN IN MY DATABASE
}
}
My code
This works on page, but I want send this to a partial, in my database I have 3 columns and I want to show the values of column there.
Partial code
I have tried many ways but I don't understand well the docs, sorry for my English. If someone help me I would be grateful.

I am assuming you have this onRequest function on a component so write below code on it.
public function onRun(){
$this->page['users'] = $this->onRequest();
}
public function onRequest(){
return \Db::table('engegraph_forms_membros')->get();
}
now users variable will be available on your page and partial.

Related

How can i fetch dynamic data from database based on selected language.?

Hi i am working on a project in laravel 7.0, in back-end i have a table called Posts which contains 2 text language input one in french and the other is arabic added by the back-end application.
what i am trying to do is when the user uses the French Language i want the title_fr to be displayed on the view and same thing in Arabic language the title should be title_ar.
P.S data are stored in French and Arabic
I have tried the similar solution given in an other similar question but none of it worked in my case!
Any idea how i might get this to work ?
Thanks in advance.
You can do something similar to below. We have a model Post, this model has an attribute title. I also assume that you have an attribute that will return user's language from the User model.
class Post extends Model
{
public function getTitleAttribute(): string
{
return Auth::user()->language === 'fr' ? $this->title_fr : $this->title_ar;
}
}
FYI above is just a demo on what can be done. For a full blow solution I would recommend decorator pattern.
Also it might be worth considering using morph for things like that. You can have a service provider that will initiate the morph map for you post model relevant to the language that user has, I.e.
Class ModelProvider {
Protected $models = [
‘fr’ => [
‘post’ => App/Models/Fr/Post::class,
],
‘ar’ => [
‘post’ => App/Models/Ar/Post::class,
]
];
Public function boot() {
$language = Auth::user()->Settings->language;
Relation::morphMap($This->models[$language]);
}
}
Afterwards you just need to call to Relation::getMorphModel(‘post’) to grab Post class that will return correct language.
I.e. App/Models/Fr/Post can have a an attribute title:
Public function getTitleAttribute(): string {
Return $this->title_fr;
}
For example above you would also want to utilise interfaces to make sure that all models follow the same contract, something below would do the trick:
Interface I18nPostInterface {
Public function getTitleAttribute(): string
}
Also, depending on the database you use, to store titles (and other language data) in a JSON format in the database. MySQL 8 has an improve support for JSON data, but there are limitations with that.
So I was Able to fetch data from my database based on the Language selected by the user.
Like i said before I have a table called Posts and has columns id,title_fr and title_ar. I am using laravel Localization.
Inside my PostController in the index function i added this code:
public function index()
{
//
$post = Post::all();
$Frtitle = post::get()->pluck('title_fr');
$Artitle = post::get()->pluck('title_ar');
return view('post.index',compact('post','Frtitle','Artitle'));
}
if anyone has a better way then mine please let me know, i am sure
there is a better way.

push an array while foreach other array laravel

I'm using laravel package commentable by faustbrian. i've been getting the comment for a post using just like in documentation in github . I want to search the information for user who post the comment, e.g the user avatar, address, and other information as well. I want to include the user information (which is an array) to the current position index of array (while for each i push it). the problem is, i tried using array_push, array_merge and $data[$key]=>$value as well. but none of them is working when i dd the variable. please help.
public function notaPengurusan($id){
$comments=Complaint::findOrFail($id)->comments->toArray();
foreach ($comments as $comment){
$creator=User::findOrFail($comment['creator_id'])->toArray();
array_push($comment,$creator);
}
dd($comments);
return view('complaint::notapengurusan',compact('comments'));
}
image when i dd the image
You need to use array index and its global variable $comments
foreach ($comments as $key=>$comment){
$creator=User::findOrFail($comment['creator_id'])->toArray();
array_push($comments[$key],$creator);
}
you should add user() relationship in your Comment Model :
public function user(){
return $this->belongsTo('App\Model\User','creator_id');
}
then no need to use for loop and finding user each time , use with('user'):
$comments=Comment::where(['post_id'=>$post_id])->with('user')->orderBy('created_at','desc')->paginate(12);

Undefined variable in view

I am having an issue setting variables in the controller and showing it at the view.
my codes are as follow:
In my view (pages/anything.ctp):
<?php echo $anything; ?>
In my controller (pagesController.php):
public function anything() {
$a = "asdasdas";
$this->set('anything', $a);
}
I am new to Cake, and I've done quite a number of search in google and stack. Still no luck.
I'd be grateful if anybody could help, or if anyone already asked this question before please provide a link that would be best.
First read the following article Controller actions in CakePHP CookBook
When you use controller methods with requestAction(), you will often want to return data that isn’t a string. If you have controller methods that are used for normal web requests + requestAction, you should check the request type before returning:
class RecipesController extends AppController {
public function popular() {
$popular = $this->Recipe->popular();
if (!empty($this->request->params['requested'])) {
return $popular;
}
$this->set('popular', $popular);
}
}
The above controller action is an example of how a method can be used with requestAction() and normal requests. Returning array data to a non-requestAction request will cause errors and should be avoided. See the section on requestAction() for more tips on using requestAction()
Try this:
public function anything() {
$a = "asdasdas";
$this->set(compact('a'));
}
<?php echo $a; ?>

AuthComponent::user('id') not returning correct data

In my AppModel, I have a beforeSave function:
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['created'])) {
$this->data[$this->alias]['created'] = date('Y-m-d G:i:s');
$this->data[$this->alias]['modified'] = $this->data[$this->alias]['created'];
} else {
$this->data[$this->alias]['modified'] = date('Y-m-d G:i:s');
}
$this->data[$this->alias]['modified_by'] = AuthComponent::user('id');
return true;
}
It's a simple function that just records the created and modified dates, and sets a field modified_by to the id of the currently logged in user. Or at least that's what it's supposed to do, everything works except getting the id of the currently logged in user, and I can't figure out why, because as far as I can tell in the documentation, that's exactly how it should be called.
I figured out my issue, and I feel a little dumb because of it, but thought I would add it here in case anyone else runs into the same problem.
In my News model, I was also calling the beforeSave function as well, but I forgot a line in it, namely parent::beforeSave();. How the date stuff in the beforeSave function was working, I don't know, but this fixed my problem of part of the beforeSave function not working.
Thanks for everyone's help in this matter, it's appreciated.
why not grab your user id from
CakeSession::read( 'Auth.User.Id ) ?
I think you should set user id in AppControlle::beforeFiler() method instead of AppModel
$this->data[$this->modelClass]['modified_by'] = $this->Auth->User('id');

CakePHP 2.0 Accessing model field values for view/controller comparisons - Only letting users edit/delete their own posted items

I am fairly new to CakePHP, I am trying to only allow those users who created an event to be able to edit or delete an event, so I am comparing the current user id, with the 'user_id' field of the event the current event (saved when a user creates an event). Any help would be appreciated thanks, my code(Andrew Perk) is as follows:
public function isAuthorized($user) {
$this->loadModel('User');
if ($user['role'] == 'admin') {
return true;
}
if (in_array($this->action, array('edit', 'delete'))) {
if ($user['id'] != $this->request->data['Event']['user_id']) { ///THIS IS THE LINE I FEEL IS WRONG - PLEASE ADVISE
//echo debug($event['user_id']);
//$this->Session->setFlash(__('You are not allowed to edit someones event'));
return false;
}
}
return true;
}
There are a few ways you can accomplish this. The one I have found that usually works best is to put a callback in the model that will set the user_id for the record you are trying to modify. Then it doesn't have to get all mixed up in controller everywhere you are trying to CRUD a record.
You can read more about limiting user data here: http://blogchuck.com/2010/06/limit-data-by-user-with-cakephp/
This will also apply to deleting data.
Hope it helps. Happy coding!

Resources