Laravel Eloquent Get the data of foreign key also [closed] - laravel

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to get the data of a Model and also the data of the foreign key in the Model
For Example:
A Post Model has a user_id as a foreign key. How can I write an Eloquent query so that I can get the data of a Post and in place of the user_id, I get the data of the user_id ?

Use with method when querying your post to include the user.
$post = Post::with('user')->first();
// or
$posts = Post::with('user')->get();

At Post model
public function user(){
return $this->belongsTo(User::class,'user_id');
}
Now at your PostController
Guess you have a method which is use for showing post
public function show($id){
$post = Post::query()->findOrFail($id);
}
Now if you want to access which user posted then there has two ways.
Way 1 :
public function show($id){
$post = Post::query()->with('user')->findOrFail($id);
}
Way 2 :
public function show($id){
$post = Post::query()->findOrFail($id);
echo $post->user->firstName;
}
Note :
If you just write $post->user then it will show/return User table according to user_id column.
If you want to access these user row column then . Simply $post->user->column_name;
Enjoy Coding.

Related

where could i be wrong? Trying to get property 'title' of non-object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
when trying to view a specific blog article i get the error Trying to get property 'title' of non-object
here is my controller controller code
public function theblog(Request $req, $slug){
$blog = blog::find($slug);
DB::table("blogs")->where('slug', "$slug")->increment('views');
return view('myblog',compact('blog'));
}
public function theblog(Request $req, $slug){
$blog = blog::where('slug', $slug)->firstOrFail();
DB::table("blogs")->where('slug', $slug)->increment('views');
return view('myblog',compact('blog'));
}
Some tips.
your primary key is unlikely to be 'slug' so you need to use a where
don't quote php parameters
your classes should start with an uppercase, ie Blog not blog
you should probably only increment views once per user
public function theblog(Request $req, $slug){ $blog = blog::find($slug);
dd($slug);
DB::table("blogs")->where('slug', "$slug")->increment('views'); return view('myblog',compact('blog')); }
Check if there is value for $blog...if it is null(that is the problem) then you should check you DB?

Laravel retrieve relationship data via another relationship

I have three tables
Question table:
id
title
description
Answer table:
id
answerbody
question_id
Likes table:
id
answer_id
I want to retrieve single question details with all the answers and answer_count and their respective likes (only like_count)
I tried this
public function show($id)
{
return question::with(['answers','answers.likes'])->withCount(['answers'])->where('id',$id)-
>get();
}
How do I return likes with count?
If you need all answers for a question and along with their likes count you can call a closure inside your with() clause and load their related likes count as
Question::with(['answers'=> function ($query) {
$query->withCount('likes')
->orderBy('likes_count', 'desc');
}])
->withCount(['answers'])
->where('id',$id)
->get();
This way you can also sort the answers based on their likes count
Each question has many answers. So in the Question model add the below code :
public function answer()
{
return $this->hasMany(Answer::class);
}
Each answer has many likes. So in the Answer model add the below code :
public function likes()
{
return $this->hasMany(Like::class);
}
Now you have to define a mutator "getDataAttribute" as below in the Question model:
public function getDataAttribute()
{
return [
'question' => $this,
'answers' => $this->answers()->get(),
'answer_count' => $this->answers()->get()->count(),
'likes' => $this->answers()->likes()->get(),
];
}
Finally, anywhere you needed the question information you just need to invoke :
$question->data
to retrieve question, likes and question count.

Access id of first foreach loop in second loop when where condition is met [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
$data['customers'] = DB::table('master_customer')->where('ORG_ID', $user_org)->get();//customer table
$document_cat = DB::table('document_category')->get();//category table
foreach ($data['customers'] as $key => $value) {
foreach ($document_cat as $key1 => $value1) {
$docs = DB::table('master_documents')//docuements saved in this table
->where('cust_id', $value->id)
->get();
$document_cat[$key1]->doc = $docs;
}
$data['customers'][$key]->documents = $document_cat;
}
print_r($data);
die;
Why you dont update eloquent relationships in models? If you do so it could be much easier.
MasterCustemer Model
public function masterDocuments()
{
return $this->hasMany('App\correctfoldertoothermodel\MasterDocument','cust_id');
}
MasterDocument Model
public function masterCustomer()
{
return $this->belongsTo('App\correctfoldertoothermodel\MasterCustomer','cust_id');
}
public function documentCategory()
{
return $this->belongsTo('App\correctfoldertoothermodel\DocumentCategory');
}
DocumentCategory Model
public function masterDocuments()
{
return $this->hasMany('App\correctfoldertoothermodel\MasterDocument');
}
Of course you'll have to provide the correct table names in migration for auto implementation of fk or set tables in relationships too.
When it's done you could retrieve data like it:
$masterCustomers->with('masterDocuments.documentCategory')->get();
$masterCustomers->masterDocuments = $masterCustomers->masterDocuments->groupBy(function($item){
return $item->documentCategory->name;
});
The result will be a collection of customers with and property containing an another collection of categories with its documents.

How to bind a parameter to Cart::create in Laravel? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to store current user's user_id in database in Laravel:
public function AddToCart(Request $request)
{
Cart::create([
'user_id'=>Auth::user()->id,
'product_id'=>$request->AddToCart
]);
return redirect('#');
}
Here user_id is an attribute and $userId is the user's id which I want to store in the database. But I am getting the following error:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
it's very simple with laravel. you can do it like this; also we need to check if the user it is actually authenticate d
if (Auth::user()) {
Cart::create([
'user_id' => Auth::user()->id,
'product_id' => $request->AddToCart
]);
}
don't forget to use Illuminate\Support\Facades\Auth; at the top of your class.
For the error that you are getting, one possible solution could be to create a new migration: php artisan make:migration modify_user_id_in_carts_tabel --table=carts and add the following: note that you may need to run composer require doctrine/dbal if you dont have it.
$table->unsignedInteger('user_id')->nullable()->change();

Database relation with Laravel Eloquent ORM

I'm new to Laravel and I'm stuck. This is what I am struggling with:
$questions = Question::find($id)->quiz(); // this code retrieves data from
// the table using the primary key
// in the table. The is a parameter
// that is passed via get.
This is what I have right now:
$questions = Question::where('quiz_id', '=', $id)->quiz();
This is the error I get:
Call to undefined method Illuminate\Database\Query\Builder::quiz()
What I want to do:
I want to run a query to get data from my database table using the foreign key in the table not the primary key, I also want to be able to use relations with this as seen from what I tried to do above.
Edit: Added the Question Model
<?php
class Question extends Eloquent{
protected $table = 'quiz_questions';
public function quiz()
{
return $this->belongsTo('Quiz');
}
}
Calling the quiz() function from Question::find($id)->quiz() will return a Query Builder instance allowing you to query the parent of the Question, its not going to return any data at that point until you call ->get() or another method that actually executes the query.
If you're wanting to return all the questions belonging to a certain quiz then you can do it like this.
$questions = Question::where('quiz_id', $id)->get();
This will return an Eloquent\Collection of the results for all questions with a quiz_id that is equal to $id.
If you've setup the relations between the Quiz and Questions then you can also do this using the Laravel relations.
$quiz = Quiz::findOrFail($id);
foreach($quiz->questions as $question)
{
// Do stuff with $question
}
Laravel will automagically pull Questions from the database that belongTo the Quiz you've already got from the database, this is known as eager loading http://laravel.com/docs/4.2/eloquent#eager-loading
Wader is correct, just calling where() will not execute your query. You either call get() and get an iterable result or use first() if you only want one result.
$quiz = Question::where('quiz_id', '=', $id)->first()->quiz();

Resources