Laravel belongs returns none - php

I have a user model, which can have many reports, and a report model obviously belonging to a user, whenever one is created.
However when I use return $this->belongsTo('App\User') on the report model No user is returned even when I have the correct user_id on the report, and correct id on the user table.
User
protected $fillable = [
'name', 'email', 'password',
];
public function reports()
{
return $this->hasMany('App\Report');
}
Report
protected $fillable = [
'user_id', 'title', 'detail',
];
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}

I've solved it simply by using $report->user, instead of calling it like a function via $report->user()

Related

Accessing The Laravel SQL Relationship without Local Key

I am new in Laravel. I have two models: User and Car. I wish to access the car data from the user entity in the controller, but I could not find how to do it. In addition, the database is fixed with the columns and the administrator refuses to do any change on it.
Here is the User model:
class User extends Model {
protected $primaryKey = 'idUser';
protected $fillable = [
'name', 'age', 'address', 'gender', 'phone', 'email'
];
}
And then this is my Car model:
class Car extends Model {
protected $primaryKey = 'idCar';
protected $fillable = [
'carNumber', 'carMachineNumber', 'type', 'model', 'year', 'idUser'
];
public user(){
return $this->belongsTo(User::class, 'idUser');
}
}
In the controller and the blade templates, I wish I can access the car data from the user entity. For example when I want to get the car type data then I would access it by:
$user->car->type
It would be even better if I will be able to access all of the cars a user has by this line of code:
$user->car->all();
How to make it possible? What should I add to the controllers without making any change to database? Thanks.
You don't have standard primary key id, so you will have to specify all the keys in the relationship (idCar).
Car model
public function user() {
return $this->belongsTo(User::class, 'idUser', 'idCar');
}
But this will get you $car->user which is the owner of the car.
With the way you designed your database, a user can have many cars.
User model
public function cars() {
return $this->hasMany(Car::class, 'idUser', 'idUser');
}
When you want to retrieve the cars belong to a user, you can
$user->cars;
or
foreach($user->cars as $car) {
// $car
}

how can I get data from multiple related tables in Laravel

I have three tables: events - admins - dependencies
The relationship between them is the following:
a dependency has many admins, an admin has many events
like that:
I'm trying to show the name of the dependency to which the admin that created the event belongs.
How could I bring data with Laravel from this three tables?
controller:
class WelcomeController extends Controller
{
public function evento($slug){
$event = Event::where('slug', $slug)->first();
return view('evento', compact('event'));
}
Event model:
class Event extends Model
{
protected $fillable = [
'admin_id', 'place_id', 'name', 'slug', 'excerpt', 'body', 'status', 'file'
];
public function admins(){
return $this->belongsTo('App\Admin', 'admin_id');
}
Admin model:
protected $fillable = [
'name', 'email', 'password', 'cargo', 'dependence_id'
];
public function dependencyAdmin(){
return $this->belongsTo(Dependence::class);
}
Dependence Model:
class Dependence extends Model
{
protected $fillable = [
'name', 'slug'
];
public function adminsDependence(){
return $this->hasMany(Admin::class);
}
So I try to show it in the view, but it does not work:
<div class="panel-heading">
Dependencia:
{{$event->admins->dependencyAdmin->name}}
</div>
The problem is that you're only retrieving the event model without loading the relationship. See here for more explanation
$event = Event::where('slug', $slug)->first();
$eventAdmins = $event->admins()->get();
$eventAdminDependency = $eventAdmins->dependencyAdmin()->get();

How can I get all the users that has commented a post?

I'm working with Laravel 5 and I've the following Models
PostComment.php
class PostComment extends Model
{
protected $fillable = [
'post_group_id', 'user_id', 'comment_content'
];
public function post(){
return $this->belongsTo('App\PostGroup');
}
public function user(){
return $this->belongsTo('App\User');
}
}
PostGroup.php
class PostGroup extends Model
{
protected $fillable = [
'group_id', 'user_id', 'post_content'
];
public function user(){
return $this->belongsTo('App\User');
}
public function group(){
return $this->belongsTo('App\Group');
}
public function commented(){
return $this->hasMany(
'App\PostComment'
);
}
}
Group.php
class Group extends Model
{
protected $fillable = ([
'id'
]);
public function users(){
return $this->belongsToMany(
'App\User',
'user_group'
);
}
public function members(){
return $this->belongsToMany(
'App\User',
'user_group'
)->wherePivot('state','accepted');
}
public function posted(){
return $this->hasMany(
'App\PostGroup'
);
}
}
My web application presents groups, in which you can create posts and in which post you can write comments. In my database I've the following relationships:
Group: (id, name, description);
PostGroup: (id, group_id, user_id, post_content);
PostComment: (id, post_group_id, user_id, comment_content);
What I want to do is to create a collection of User objects, and then make a query to get all users, subscribed to a group, who have commented on a certain post, in MySQL looks like:
select users.* from users, post_comments where users.id = post_comments.user_id and post_comments.post_group_id="1"
So in my controller I've the following code
$theGroup = Group::find($groupId);
$thePost = PostGroup::find($postId);
$memberList = User::where('id', '<>', Auth::user()->id)->whereIn('id', $theGroup->users->pluck('id'))->
So, what I want to do is to extend that query to get the desidered result with ->get()->sortBy('last_name');, how can I exted it after the whereIn?
EDIT
User.php
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token','created_at','updated_at'
];
public function groups(){
return $this->belongsToMany('App\Group','user_group');
}
public function groupsAsAdmin(){
return $this->belongsToMany('App\Group','user_group')->wherePivot('role','admin');
}
public function groupsAsMember(){
return $this->belongsToMany('App\Group','user_group')->wherePivot('state','accepted');
}
public function groupsAsInvited(){
return $this->belongsToMany('App\Group','user_group')->wherePivot('state','pending');
}
public function posted(){
return $this->hasMany('App\PostGroup');
}
public function commented(){
return $this->hasMany('App\PostComment');
}
}
From your description, you already come up with a list of Users in advance, so that you only will find Posts with a Comment of these specific users.
Basically, what you want is to use whereHas($relation, $calback) to perform the checks you described:
$userIds = [2, 3, 5, 7, 11, 13, 17]; // or query them...
$postId = 123; // the id of the post where we want to look through the comments
User::where('id', '<>', Auth::id())
->whereIn('id', $userIds)
->whereHas('comments', function ($query) use ($postId) {
$query->where('post_group_id', $postId);
})
->get();
This will simply check if a user has written a Comment for the given post. Because you forgot to post your User model, I assumed that there is a relation available for the comments of the user.
You could also combine the first two conditions (user in list, but not the authenticated one) into one, if you want. $userIds = array_diff($userId, [Auth::id()]) does the job. where('id', '<>', Auth::id()) can be dropped from the query then.
If you do also need to check for an active subscription of the user to a group, it will be slightly more complex. But as you commented, you are already finding only users for a group, so this should be fine.
In PostComment, try this
$this->selectRaw(‘user_id, comment_content’)->where(‘post_group_id’, 1)->groupBy(‘user_id’)->get();

Laravel - Eloquent attach() not working for models

TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}

How to auto fill foreign key column value in Laravel 5.2?

I'm working on laravel 5.2 and also beginner of laravel. I have users and clients table in the database. user field of clients table stores the value of id column(primary key) of users table. i.e, one user have many clients and one client belongs to one user. Now come to problem. When I'm going to insert new client of the logged in user, I'm getting error. No any error message. I searched and come to know that perhaps it happens because of foreign key column name is user, not user_id. So I updated my Client model from return $this->belongsTo('App\User'); to return $this->belongsTo('App\User', 'user');. But still failed. If any one knows the answer, answer will be appreciated. Here is my code.
ClientController (Try 1)
$request->user()->clients()->create([
'user' => $request->user()->id,
'email' => $request->email,
'age' => $request->age
]);
ClientController (Try 2)
$request->user()->clients()->create([
'email' => $request->email,
'age' => $request->age
]);
Client Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Ak\Scopes\AgeScope;
class Client extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new AgeScope);
}
public function user()
{
return $this->belongsTo('App\User', 'user');
}
}
User Model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'country'
];
protected $hidden = [
'password', 'remember_token',
];
protected $date = ['deleted_at'];
public function client()
{
return $this->hasMany('App\Client', 'user');
}
}
sorry your relationship is wrong. and moreover you are using
$request->user()->clients()
instead of
$request->user()->client()
the client in your relationship is singular. And the client function body should be
return $this->hasMany('App\Client', 'user');
and in your client model add
$fillable = ['email', 'age', 'user'];
and change the user function in your client model to
public function user()
{
return $this->belongsTo('App\User', 'user');
}
the orm should be like this
$request->user()->client()->create([
'user' => $request->user()->id,
'email' => $request->email,
'age' => $request->age
]);
Try adding protected $fillable = ['email', 'age']; to your Client model.
More on mass assignement
Edit:
try this
Routes:
Route::post('user/{user}/client', 'YourController#store');
Controller:
public function store(Request $request, User, $user){
$user->client()->create([
'user' => $request->user()->id,
'email' => $request->email,
'age' => $request->age
]);
}
Problem is Solved
Problem is solved as I have to write public $timestamps = false; in Client Mode. After it, I don't need to insert user value manually. Because laravel is doing that task itself as I have write foreign key in User and Client Models relationship. i.e, return $this->hasMany('App\Client', 'user') and return $this->belongsTo('App\User', 'user') manually.
I can't understand that what should I do for this feature of laravel. Should I cry or laugh?

Categories