How can i change key id in method class orm Laravel? - laravel-5

Maybe is not possible but i have in table answers for radio input with id of question and answer like id = 36 , answer = Yes. My code below get all answers
public function getAnswer() {
return $this->hasMany('App\Answer', 'user_id', 'id')
->with('question')
->whereHas('question.group', function($query) {
$query->where('name', 'simple_quesion');
});
}
and i have collection which is ok
#items: array:9 [▼
0 => getAnswer {#400 ▶}
1 => getAnswer {#401 ▶}
2 => getAnswer {#402 ▶}
but is any way to get keys and assign with this collection like
#items: array:9 [▼
35 => getAnswer {#400 ▶}
37 => getAnswer {#401 ▶}
42 => getAnswer {#402 ▶}
in this method public function getAnswer() ?
[UPDATE]
full collection
Collection {#396 ▼
#items: array:9 [▼
0 => getAnswer {#400 ▼
#fillable: array:3 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 18
"user_id" => 11
"answer_id" => 34
"answer" => "YES"
]
#original: array:7 [▶]
#changes: []
And i need key answer_id => 34
#items: array:9 [▼
34 => getAnswer {#400 ▼

Ok i am so stupid. This is so easy. In blade or controller i can use:
{{ dd($user->getAnswer->pluck('answer', 'answer_id')) }}

Try this:
In Answer model, add this:
public function question(){
return $this->belongsTo("App\Question"); //the column name of the question should be "question_id"
}
in Question model, do:
public function answers(){
return $this->hasMany("App\Answer");
}
And in your controller, where you want to get the question and its answers, you just do:
Question::with('answers')->all(); //assuming you want to get all the questions and their answers

Related

Foreach loop not showing results in view

I'm trying to list answers from my database. But I only get blank page even though when I run dd it shows the collection. Here's the relevant code:
Controller file:
public function index($subject_id, Request $request)
{
$answers=AnalizaAnswer::where('subject_id', $subject_id)->get();
return view('analiza.index', compact('answers'));
}
View:
<ul>
#foreach ($answers as $answer)
<li>{{$answer->answer}}</li>
#endforeach
</ul>
I get a blank page but dd($answers) returns this:
Collection {#357 ▼
#items: array:6 [▼
0 => AnalizaAnswer {#358 ▼
#guarded: []
#connection: "mysql"
#table: "analiza_answers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▶]
#original: array:6 [▼
"created_at" => "2019-09-07 16:38:45"
"updated_at" => "2019-09-07 16:38:45"
"analiza_question_id" => 1
"subject_id" => 3
"user_id" => 56
"answer" => "Ne"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
1 => AnalizaAnswer {#359 ▶}
2 => AnalizaAnswer {#360 ▶}
3 => AnalizaAnswer {#361 ▶}
4 => AnalizaAnswer {#362 ▶}
5 => AnalizaAnswer {#363 ▶}
]
}
I tried $answer['answer'] but same result. I should mention that I have a triple composite primary key for this table so might be that.

Laravel, get relation data

I'm kinda new to relations in Laravel.
When I do ddof an object, I get this:
Collection {#485 ▼
#items: array:1 [▼
0 => Menu {#484 ▼
#table: "menus"
#fillable: array:6 []
#hidden: array:2 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 []
#original: array:11 []
#relations: array:2 [▼
"pivot" => Pivot {#486 ▶}
"subMenus" => Collection {#items: array:3 [▼
0 => SubMenu {#488 ▼
#table: "sub_menus"
#fillable: array:5 []
#hidden: array:2 []
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:8 []
#original: array:10 [▼
"id" => 16
"name" => "My name" <--------- this is what I need to get
"created_at" => "2018-11-20 15:19:14"
"updated_at" => "2018-11-20 20:29:34"
How can I get the namevalue from the Model SubMenu that has a relation with my dd(model) ?
In Menu I got thos relation:
public function subMenus()
{
return $this->belongsToMany('App\SubMenu', 'menu_submenu', 'menu_id', 'submenu_id')->where('estado', Define::ESTADO_ACTIVO)->orderBy('orden');
}
I tried something like:
dd($MyMenuObject->subMenus());
but not working. Tried with get(), ->submenu, etc.
EDIT: This is my data:
with dd($perfil_activo->menus); I get:
You can access it via
$model->subMenus()->first()->name;
But since $subMenus() is a many-to-many relationship, you should probably do this via a loop:
foreach($model->subMenus AS $subMenu){
$subMenu->name; // Do with as you please.
}
Edit: Since $model is also a Collection, you need to use ->first() or a loop:
$model->first()->subMenus->first()->name;
// OR
foreach($model AS $model){
$model->subMenus->first()->name;
// OR
foreach($model->subMenus AS $subMenu){
$subMenu->name;
}
}
This is all dependant on how you fetch $model; if your Query ends with a ->get() or ->all(), it will be a Collection. If it ends with ->first(), ->find(), etc, it will be a single Model.
You can list all the subMenu names on an array: or object
$names=$model->subMenus()->pluck('name'); //object
//or
$names=$model->subMenus()->pluck('name')->toArray();// to array
dd($names);

Laravel change collection attributes name

How would you change the attributes from a collection?
So the return is a Collection of Models with changed attributes, and not a Collection of arrays.
The things is, I would like to make some kinda of translation presenter, so when I get the collection I could dd($collection) and instead of 'name' it would show 'nome', also using response()->json($collection) would show the changed named.
so something like $presenterNames = ['name' => 'nome', 'id' => 'identificador']; and the names that aren't here would call normally.
Collection {#213 ▼
#items: array:2 [▼
0 => Category {#215 ▼
+timestamps: false
#fillable: array:2 [▶]
#connection: "mysql"
#table: "categories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:3 [▼
"id" => 1
"name" => "categoria1"
"slug" => "categoria1"
]
#original: array:3 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
#slugOptions: null
}
1 => Category {#219 ▶}
]
}
so basically I would like to change
#attributes: array:3 [▼
"id" => 1
"name" => "categoria1"
"slug" => "categoria1"
]
to this
#attributes: array:3 [▼
"identificador" => 1
"nome" => "categoria1"
"slug" => "categoria1"
]
Dinamicaly by using a assoc array.
Solution :
In your Model add below code.
protected $appends = ['nome'];
public function getNomeAttribute(){
return $this->attributes['name'];
}
You can access it by querying $modelObj->nome;
Do the same for all needed attributes.
This will also reflect in your JSON response.
Thanks
Reference : https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

Accessing Users of a group

I make the following query
$group = Group::with('user.campaign')->where('groupName', 'TeamA')->get();
This returns something like the following
Collection {#429 ▼
#items: array:1 [▼
0 => Group {#398 ▼
#table: "user_groups"
#guarded: []
#attributes: array:5 [▶]
#original: array:5 [▶]
#relations: array:1 [▼
"User" => Collection {#402 ▼
#items: array:5 [▼
0 => User {#409 ▶}
1 => User {#410 ▶}
2 => User {#411 ▶}
3 => User {#412 ▶}
4 => User {#413 ▶}
]
}
]
#hidden: []
#visible: []
#appends: []
#fillable: []
}
]
}
So I can see User is within the relations. However, I am having issues accessing the users which are apart of the Group TeamA.
If I try
$group->user
I get an error. Unfortunately, my error page at the moment only seems to say something went wrong, without any details.
How would I go about accessing the users of this group?
Thanks
i think you have some mistake on that , User field is a collection ...
that mean , User field is not instance of User class and is collection of users
"User" => Collection {#402 ▼
#items: array:5 [▼
0 => User {#409 ▶}
1 => User {#410 ▶}
2 => User {#411 ▶}
3 => User {#412 ▶}
4 => User {#413 ▶}
]
}
i suggest you to rename User field in Team class to Users.
after that it's good to know, property name should be camel case ...

Laravel 5 Array to View

Can some please tell me how to display the results of this array in a view in Laravel 5?
RowCollection {#464 ▼
#title: "Worksheet"
#items: array:3 [▼
0 => CellCollection {#472 ▼
#title: null
#items: array:2 [▼
"name" => "Owen Kelley"
"age" => 29.0
]
}
1 => CellCollection {#473 ▼
#title: null
#items: array:2 [▼
"name" => "Jim Jackson"
"age" => 50.0
]
}
2 => CellCollection {#474 ▼
#title: null
#items: array:2 [▼
"name" => "Sally Anne"
"age" => 35.0
]
}
]
}
I have been struggling with this for ages!
Many thanks.
You should use foreach, example:
In controller/routes.php:
return view('yourviewname')->with('elephants', 'elephants')
In blade view:
#foreach($elephants as $elephant)
{{ $elephant->name }}
#endforeach

Resources