php - Getting an empty array when trying to retrieve data from a one to many relationship Laravel
Get the solution ↓↓↓I am working a on a platform that allows student search and get a house. I am trying to implement a feature that allows students rate a agent base on what the agent post so as to reduce and moderate scam on the platform. Even after I established a one to many relationship between User(agent) and AgentRating, I get null when I try to retrieve an agent rating.
AgentRating.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AgentRating extends Model
{
//
public function user(){
return $this->belongsTo(User::class);
}
}
User.php
class User extends Model
{
public function ratings(){
return $this->hasMany(AgentRating::class);
}
}
AgentRatingController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\AgentRating;
use App\Http\Traits\AuthUserTrait;
use DB;
class AgentRatingController extends Controller
{
//
use AuthUserTrait;
public function __construct(){
$this->middleware(['jwt.auth', 'forceJson'], ['only' => ['store']]);
}
public function store(Request $request, $id){
$this->validate($request, [
"rating" => 'required'
]);
$rating = new AgentRating;
$user = User::find($id);
$rating->user_id = $this->authUser()->id;
$rating->agent_id = $user->id;
$rating->rating = $request['rating'];
$rating->save();
dd($user->ratings); // This returns an empty array even though there is a rating saved to the DB.
}
}
Answer
Solution:
I think there is a typo in yourAgentRatingController
.
$rating->agent_id = $user->id;
line seems wrong.
The$rating_id
should be auto incremental and not fillable. Isn't?
Also, I recommend you to follow the PSR-12 standard when programming. I mean, declare the property types, the function returning values and the spaces like:
public function store(AgentRatingRequest $request, int $id): void
{
AgentRating::create([
'user_id' => auth()->id(),
'rating' => $request['rating'],
]);
dd($user->ratings);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: deprecated: directive 'allow_url_include' is deprecated in unknown on line 0
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.