Property [user] does not exist on this collection instance - laravel

i'm developping a social app using React in the frontend and laravel in the backend.
I'm trying to receive all posts with their likes,users,comments. I have these relation ships:
1/ User model has many posts and Post model belongs to a user.
2/ Post model has many likes
3/ Post model has many comments and one comment belongs to a user.
When getting all posts back, im succefully getting its likes and users information, but for comments i wanna get the user's comment. So i did $posts->comments->user->user_name
And then, i got the error: Property [user] does not exist on this collection instance. But when i tried to get comments infos, it worked normally($posts->comments)
My comment relation in Post model:
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
My user relation in Comment Model:
public function user()
{
return $this->belongsTo('App\Models\User');
}
My method in PostController when i'm trying to get all posts:
public function allPosts()
{
$posts = Post::with('user','likes','comments')->get();
if($posts->count() < 1) {
return response()->json([
'success' => false,
'message' => 'There are no posts!'
]);
}else {
return response()->json([
'success' => true,
'data' => PostResource::collection($posts),
'message' => 'Succefully retreived all posts!'
]);
}
}
As you noticed i'm sending the Data through a Resource, so My PostResource's method :
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'user_id' => $this->user_id,
'content' => $this->content,
'image_path' => $this->image_path,
'user' => $this->user,
'likes' => $this->likes->count(),
'isLiked' => $this->likes->where('user_id', auth()->user()->id)->isEmpty() ? false : true,
'comment_user' => $this->comments->user->user_name,
'created_at' => $this->created_at->format('d/m/y'),
'updated_at' => $this->updated_at->format('d/m/y')
];
}
As i said, everything is okey, just for comment_user it says:Property [user] does not exist on this collection instance, and when i tried to get only comments info it worked:
'comments' => $this->comments,
Any help please? and thnx in advance.

Maybe you need to add relation user() to Post model?

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Pass Session Data From Controller to View in Laravel 6

I want to create edit user account feature in my Laravel project, so i want to pass current session data from controller to view but i got an error Trying to get property 'name' of non-object. Before passing data, i create login feature to get session, here is my LoginController to get session:
public function loginprocess(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->route('index.user');
}
return back()->withInput($request->only('email', 'remember'));
}
Then in another controller i create this function:
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',$data);
}
And in the view i use this code:
{{ $account->name }}
In database user i sure I make sure in the user table there is a name field. I try to get {{ $titleweddinc }} and it can appeat. Does anyone know what my mistake is?
use like this
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',compact('data'));
}
If Object then print like
{{ $data->account->name}}
Check if Array then print like
{{ $data['account']['name']}}

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Two store() methods, one doesn't work (Call to undefined method save())

One of two similar store methods doesn't work. Could you clarify this for me?
Relations
A Team hasMany Users <> A User belongsTo a Team
A User hasMany Characters <> A Character belongsTo a User
Working Code (CharacterController)
public function store()
{
$fighters = Fighter::pluck('name')->toArray();
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|not_in:'.Rule::notIn($fighters).'unique:characters',
'fighter' => 'required|in:'.Rule::in($fighters),
]);
auth()->user()->characters()->save(new Character([
'name' => request('name'),
'fighter' => request('fighter'),
]));
return redirect()->route('character.index');
}
Not Working (TeamController)
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
auth()->user()->team()->save(new Team([
'name' => request('name'),
'fame' => 0,
]));
return redirect()->route('team.index');
}
Questions
Why is the same method not available? Is it relation stuff?
Is the create method better? Should I try to use it?
Thought I know what I'm doing, now it turns out I don't...
Thank you for helping.
team() is a belongsTo relation, you probably have a team_id col in your user table which you want to associate with the team.
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
// create and save team
$team = new Team([
'name' => request('name'),
'fame' => 0,
]);
$team->save();
// associate current authenticated user with team (set foreign key) and save user
auth()->user()->team()->associate($team)->save();
return redirect()->route('team.index');
}

Yii issue retrieving relational data

I'm create a new table(s) in my Yii application thats going to be used as a relational table, just storing IDs, it's really simple, but i cannot manage to actually get any information passed through from the model, even though the IDs match. Can anyone see where i'm going wrong?
User Model (has many relations, but i've just included the one im having a problem with)
public function relations() {
return array(
'onsiteGroup' => array(self::HAS_MANY, 'EventAttendeesGroups', 'user_id'),
);
}
EventAttendeeGroups Model
class EventAttendeesGroups extends CActiveRecord
{
public function tableName()
{
return '{{event_attendees_groups}}';
}
public function rules()
{
return array(
array('user_id, group_id', 'required'),
array('user_id, group_id', 'numerical', 'integerOnly'=>true),
array('user_id, group_id', 'safe'),
array('id, user_id, group_id', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'onsiteGroupName' => array(self::BELONGS_TO, 'EventAttendeesGroupName', 'group_id'),
);
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'user_id' => 'User',
'group_id' => 'Group',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('user_id',$this->user_id);
$criteria->compare('group_id',$this->group_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
My Data is correct, the user id exists in the user table and in the EventAttendeeGroups table, yet if try the following in the user view gridview table, i get 'Not Set'
array(
'name' => 'group_id',
'type' => 'raw',
'value' => $model->onsiteGroup->group_id,
),
Can anyone see where i'm going wrong???
Are you getting an error? What is it outputting? Are you trying to render CGridView or what, and if yes is it formed?
One thought, are you sure
$model->onsiteGroup->group_id
is the object name and not
$model->onsiteGroupName->group_id
Just a thought.

Resources