ModelNotFoundException - No query results for model [App\User] - php

From the form in my edit view, I'm calling the update function:
public function update(Request $request)
{
$id = Auth::user();
$user = User::findOrFail($id);
$user->update($request->all());
return redirect('user');
}
but I'm getting the following error:
ModelNotFoundException in Builder.php line 125: No query results for model [App\User].
I'm not passing the $id because i'm updating the Auth Id.
Not sure what's wrong and how to debug

Following is just enough in case you want to update logged in User.
public function update(Request $request)
{
Auth::user()->update($request->all());
return redirect('user');
}

#pinkalvansia has a great answer and solution for you.
However, I also wanted to note that I believe you would need to use:
Auth::user()->id to get the currently logged in user's ID. Your code would like this:
public function update(Request $request)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$user->update($request->all());
return redirect('user');
}
Hope this is helpful!

Related

Call to a member function update() on null

I'm building my first Laravel app. That's my first problem that I can't overcome.
I tried to google something about it, but I couldn't find something that could help me.
class ProfilesController extends Controller
{
public function index(User $user)
{
return view('profiles.index', compact('user'));
}
public function edit(User $user){
return view('profiles.edit', compact('user'));
}
public function update(User $user){
$data = request()->validate([
'description' => 'required',
]);
$user->profile->update($data);
return redirect("{$user->id}/edit");
}
}
I want to get through that and update $data.
Edit
public function profile() {
return $this->hasOne(Profile::class);
}
public function posts(){
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
Try this:
optional($user->profile)->update($data);
You can see the official documentation of optional() helper here.
I think you cannot update directly on an instance, you'd have to do : User::where('user_id', $user->id);
If you want to "update" an instance, you would have to do : $user->description = $data['description']; $user->save();
Do this:
if($user->profile) {
$user->profile()->update($data);
}
Hope this will help you.
I would imagine this is because the user doesn't have a profile by default.
One way you can get around this is by using withDefault() on your profile relationship in your User model e.g.
public function profile()
{
return $this->hasOne(Profile::class)->withDefault();
}
You would then need to change your controller code slightly since the profile might not exist:
Change:
$user->profile->update($data);
To:
$user->profile->fill($data)->save();
I had the same issue. As it turned out I forgot to create a new empty profile while creating a new user. So i was calling an update on the user's profile in this case null.
Try adding this to the User model and later migrate:fresh your data.
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create();
});
}
This will create a new profile for user automatically.

Laravel Undefined Method

I am getting the following error on my query when the interest method exists in my model.
Call to undefined method Illuminate\Database\Query\Builder::interest()
Controller:
public function index() {
$user_id = auth()->user()->id;
$user = User::find($user_id);
$interests = Space::where('user_id', $user_id)->interest()->get();
return view('dashboard')->with('space', $user->space)->with('interest', $interests->space);
}
Space Model:
public function user(){
return $this->belongsTo(User::class);
}
public function interest(){
return $this->hasMany(Interest::class);
}
Interest Model:
public function user(){
return $this->belongsTo(User::class);
}
public function interest(){
return $this->belongsTo(Space::class);
}
Space::where('user_id', $user_id)->interest()->get();
The Line Shows Error Because the method interest is not existed in query builder or Model Scopes
But I think You have Misundestood something
Loading Relation In collection
Space::where('user_id', $user_id)->with('interest')->get();
Will Work
And
$singleFind = Space::findOrFail($yourId)->interest();
Will Work as you expected
Hope its clear
Try with this,
First of all you can access authenticated user id by this auth()->id()
For relationship in controller
$interests = Space::with(['interest'])->where('user_id', $user_id)->get();
For more
Laravel eager loading
Hope this helps:)

Cant delete users

Hello im tryng to delete users, but this function dosnt work:
public function deleteUser()
{
$user = User::find($id);
$user ->delete();
return redirect('empresa');
}
Error: Undefined variable: id
Hope this helps or answers your question. Try this;
public function deleteUser($id)
{
User::find($id)->delete();
return redirect('empresa');
}
Just to help you visualize what Nigel and Deepak are saying:
deleteUser() has to be accept an argument called $id
deleteUser($id) { ... }
So when you call deleteUser() make sure to pass in your id (parameter) value:
deleteUser(17);
Hopefully that helps you see what they're talking about.
You will first have to find your user to delete them:
$user = User::find($id);
Then you'll be able to call the delete method:
$user->delete();
You may wish to consider handling the possibility that this user might be null. There are a few ways to accomplish this:
Check if the user is null before calling delete
Using the findOrFail method when finding a user
Option 2 will throw a ModelNotFoundException which you can configure your application to handle this globally and return a 404 page or whatever you might want.
Option 1:
public function deleteUser($id)
{
$user = User::find($id);
if (null !== $user) {
$user->delete();
}
return redirect('empress');
}
Option 2:
public function deleteUser($id)
{
$user = User::findOrFail($id);
$user->delete();
return redirect('empress');
}
Notice that on Option 2 we don't need a null check as an exception is thrown if the user is not found by using findOrFail.

Error edit() must be an instance of App\User, none given

i created a UserController.php
use App\User;
//
class UsersController extends Controller
{
//
public function edit($id, User $user){
$user = $user->find($id);
return view('admin.user.edit' , compact('user'));
}
//
}
And edit views
but when i want to access to this url
url('/users/'. $user->id .'edit')
i got this error
Error edit() must be an instance of App\User, none given
!?
Make sure your route is like:
Route::get(/users/{id}/edit', 'UsersController#edit');
Then use it as:
url('/users/'. $user->id .'/edit');
or
url("/users/{$user->id}/edit");
And then your controller should be as:
public function edit($id) {
$user = User::find($id);
return view('admin.user.edit' , compact('user'));
}
The error says that the edit() function expects $user_id and User instance but you're only providing $user_id. If that's the case your code should look like this:
public function edit($id){
$user = User::find($id);
return view('admin.user.edit' , compact('user'));
}

Laravel 5.1: Call to undefined method Illuminate\Database\Query\Builder::fill()

I am trying to get this line to work $user->profile()->fill($input['profile'])->save();
Following much discussion and failed attempts
I need help filling an eloquent model
Also had a probelm with guarding
http://laravel.io/forum/01-06-2016-massassignmentexception-ignoring-fillable-guarded-is-set
Which i overcame with protected $guarded = ['id'];
Profile model
public function user(){
return $this->belongsTo('App\User');
}
User Model
public function profile(){
return $this->hasOne('App\Profile', 'user_id');
}
Controller
public function update(Request $request, $id)
{
$user = User::with('profile')->findOrFail($id);
$input = $request->all();
if(is_null($user->profile)){
$profile = new Profile($input['profile']);
$user->profile()->save($profile);
alert()->warning('New profile creation attempt!');
}else{
// $user->profile()->fill($input['profile'])->save();
$user->profile->title = $input['profile']['title'];
$user->profile->facebook_username = $input['profile']['facebook_username'];
$user->profile->meetup_user_id = $input['profile']['meetup_user_id'];
$user->profile->save();
// dump($input['profile']['title']);
// dump($user->profile->title);
//Unless it fails silently like before.
alert()->success('Profile Saved!');
}
return redirect()->route('admin.users.edit', [$id]);
}
Notice how I am manually filling, this is not ideal obviously. this is the result i am trying to achieve
as per my understanding, you want to fill profile Attributes in a single line,
did you try fill() method ??
try this way in your else section or whereever your want it, I hope that might help you
$profile = new Profile;
$profile->fill($input['profile']);
$user->profile()->save($profile);

Categories