How to get row in Laravel? - laravel

I get one row by $id in Laravel like as:
$user = User::where("id", $id)->get();
After I need to do return $user->first();
Can I use this request more shorty?

You can simply run:
return User::find($id);
or maybe (depending on your needs) even:
return User::findOrFail($id);

you donot have to call ->get() and ->first(), since you are sure that you are going to get only one result by the id column, search like this,
User::find($id);
or
User::where('id',$id)->first()
and you have other alternative methods in the case you want to handle exceptions, ->findOrFail() or ->firstOrFail()

You can use $user = User::findOrFail($id); since the id is unique so you'll either get a User object or Exception which you can catch and respond accordingly.

Since you have only one where clause, the shortest way will be
return User::find($id);

Related

Laravel Spatie Call to undefined method Illuminate\Database\Query\Builder::assignRole()

Trying to do assignRole() to many users, but it show me Call to undefined method Illuminate\Database\Query\Builder::assignRole(). Is this spatie laravel bug?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
$updateUser = \App\User::whereIn('username', $get_username);
$updateUser->assignRole('Applicant');
$updateUser->save();
Any solution for bulk assignRole() in this case?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
This is an incomplete query via the QueryBuilder. As well as the second line.
When utilizing the QueryBuilder you need to finish of your queries with the get() method to get a collection to iterate over.
The correct execution would like like this:
$get_username = \App\Applicant::select('username')->whereIn('id', $ids)->get();
Without knowing the exact result of this, it looks like you'd like to retrieve a collection of usernames, that you'd like to get the User model from.
You could do something like the following (untested) for bulk updating.:
$users = User::whereIn('username', function($query) use ($ids) {
$query->select('username')
->from('applicants')->whereIn('id', $ids);
})->get();
foreach($users as $user) {
$user->assignRole('Applicant');
$user->save();
}

Auth::user() works but Auth::user()->id breaks within a where query in eloquent?

I'm very confused by this!
In a laravel controller:
$user = Auth::user();
return $user;
returns the entire user object
$user = Auth::user()->id;
return $user;
returns the id of $user as expected
however if I put that exact thing into a query such as:
$user = Auth::user();
$query = Model::where('user_id', $user->id)->get();
return $query;
I get an error that I'm trying to get an 'id' property of a non-object!!!
How can this be possible?
I've also checked 100 times that I'm logged in when testing this.
Editing to add that I've also tried:
$query = Model::where('user_id', 1)->get();
and that works fine
edit to show the function:
$user = Auth::id();
$result = Lesson::where('user_id', $user)
->whereNotNull('notes')
->get();
return response()->json($result, 200);
Expected results: A list of objects with a filled in "notes" column.
Actual results: an empty [] and an error saying can't get id of a non-object
Don't use Auth in Models.
You can set a relation between User and your Model and do query like:
Auth::user()->relation()->get();
This error occurs if the Model doesn't contain any raw with that user id. Make sure you have the raw in the Model where you are querying to get data by user id.
You should try this
$user = Auth::user();
$result = Model::where('user_id', $user['id'])->get();
The error occurs because of you passed property of non-object.
Even after error not solve then restart your xampp or wamp.
If possible, upload the screenshot of error.
Your code should work if you are authed, it seems your are not based on the error message. Since you return json, i assume this is an api request. Api-routes uses another auth driver as default in Laravel (token vs. session). Either change the driver/guard or move your route(s) from routes/api.php to routes/web.php.
See docs for auth
You can change the driver in config/auth.php.
try this
$user_id = Auth::user()->id;
$query = Model::where('user_id', $user_id)->get();
return $query;

How can I get the laravel join method without using foreach command?

How can I get the laravel join method without using foreach command? How can I solve it without using the Foreach command
{{$app->name}} I used to this type. But I'm constantly getting error.
Controller.php file content
public function show($id)
{
$show = Duty::where('duty_id', '=', $id)->count();
if ($show!=0){
$app = DB::table('users')
->join('duties', 'duties.appointed_user_id', '=', 'users.id')
->select('users.name', 'duties.*')
->get();
$data = Duty::where('duty_id', '=', $id)->get();
return view('duty.show', compact('data', 'app'));
}
else
{
return redirect()->back()->with('status', 'Sorun oluştu');
}
}
Property [name] does not exist on this collection instance. (View: D:\xampp\htdocs\personality\resources\views\duty\show.blade.php)
You have a list (collection) of users, not a single user. That is why you can't get just the name from it, because it doesn't know which one to get the name of. This problem has nothing to do with using the join method.
If you only expect to get one result from your query, you could change from ->get() to ->first(). This would allow you to call {{$app->name}} without breaking. But only do this if you expect a single result and use first.
If you expect more than one user, there is no way to display the names without looping in some way.
That's what relationships are for. In that case you could do User::with(:duties'). Or in your case the other way around would probably work better Duty::find($id)->with('user')

Why doesn't the Collections method 'contains' work if the collection has relations?

For example:
$users = User::all();
$user = User::find(1)->get();
$sameUser = User::find(1)->with('roles')->get();
$user->is($sameUser) // true
$users->contains($user) // true
$users->contains($sameUser) // false
Shouldn't it return true for all three checks?
It's not that it isn't working with the relationship but you're messing things up with the get() calls. find() returns the instance of the user and actually calls User::where('id', '=', $id)->first(); under the hood so all of the following will return true:
$users = User::all();
$user = User::find(1);
$sameUser = User::with('roles')->find(1);
$user->is($sameUser)
$users->contains($user)
$users->contains($sameUser)
https://github.com/laravel/framework/issues/18902
technically the objects are not the same if one has eager loaded
relationships, and the other doesn't. while they may represent the
same row in the database, PHP has no way of knowing that.
in this situation you may have do it based on your primary keys.

Laravel Eloquent - update() function

Laravel's Eloquent update() function returns a boolean, and not the updated entry. I'm using:
return User::find($id)->update( Input::all() )
And this returns only a boolean. Is there a way I can get the actual row, without running another query?
I think that's the behaviour that you want:
$user = User::find($id)->fill(Input::all());
return ($user->update())?$user:false;
I hope it works fine for you.
Another approach can is to use the laravel tap helper function.
Here is an example to use it for updating and getting the updated model:
$user = User::first();
$updated = tap($user)->update([
"username" => "newUserName123"
]);
tap($user) allows us to chain any method from that model. While at the end, it will return the $user model instead of what update method returned.

Resources