I cant retrieve id from user in the database - php

When i use this code in my User model
public function get_user_by_email($email) {
$data = $this->where('email', $email);
return $data->id;
}
I get this error
Property [id] does not exist on the Eloquent builder instance.
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1602
1598▕ if ($key === 'orWhere') {
1599▕ return new HigherOrderBuilderProxy($this, $key);
1600▕ }
1601▕
➜ 1602▕ throw new Exception("Property [{$key}] does not exist on the Eloquent builder instance.");
1603▕ }
1604▕
1605▕ /**
1606▕ * Dynamically handle calls into the query instance.
1 app/Models/User.php:64
Illuminate\Database\Eloquent\Builder::__get()
2 app/Models/invite.php:21
App\Models\User::get_user_by_email()
Please help
the code should work and i have filled my database with dummy users. why cant i get my user id from the user model. I have used jetstream for this

You need to use first() on the Eloquent Builder to return the Model before you can access its attributes.
$data = $this->where('email', $email)->first();
return $data->id;

You can try in this way.
$data = Model::where('email', $email)->pluck('id');

Related

Use Model Function In Laravel Query

How Can i resolve this problem
i want select users where it has enter the tournament and i use hasEnteredTournament Function in my User model too know that
this is User model:
public function scopeHasEnteredTournament($query){
$active = Order::all()
->where('user_id','=',$this->id)
->where('status','=',1)
->where('pack_id','=',3)
->where('expired_at','>',now())
->first();
$tournament = Tournament::all()
->where('status','=',1)
->where('start_at','<',now())
->where('end_at','>',now())
->first();
if($active && $tournament){
return true;
}
return false;
}
and this is my controller codes:
$all = User::all()
->sortByDesc('tournamentPoints')
->where('hasEnteredTournament')
->take(200);
thanks very much
Since you work with collection, you can use filter method :
https://laravel.com/docs/8.x/collections#method-filter
just use this way...
$all = User::all()
->sortByDesc('tournamentPoints')
->hasEnteredTournament()
->take(200);
for more info see here https://laravel.com/docs/8.x/eloquent#local-scopes

Symfony 4 - populate array with the users of type ROLE_FITTER

Symfony 4 app using FOSUserBundle.
Trying to list users with a particular role (ROLE_FITTER) in a dropdown menu using jquery/ajax.
I'm trying to add an Action in my APIController that will get the list of users with role ROLE_FITTER and return a JSON array with them in it - so can then populate the dropdown with list of these users.
I have tried to pull together some different examples, but not sure how to correctly build the query:
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class APIController extends AbstractController
{
/**
* Returns a JSON string of the Fitters with their id.
*
* #Route(/profile/booking/new/fitters)
* #param Request $request
* #return JsonResponse
*/
public function listFitters(Request $request)
{
// Get Entity manager and repository
$em= $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select('u')
->from('userBundle:User', 'u')
->where('u.id = :user')
->andWhere('u.roles LIKE :roles')
->setParameter('user', $id)
->setParameter('roles', '%"' . $role . '"%');
$user = $qb->getQuery()->getResult();
// Serialize into an array the data that we need, in this case only name and id
$responseArray = array();
foreach ($users as $user) {
$responseArray[] = array(
"id" => $user->getId(),
"name" => $user->getName()
);
}
// Return array for dropdown
return new JsonResponse($responseArray);
}
}
How do I populate this array with the users of type ROLE_FITTER?
Well using serialized strings in sql is never a good idea, no idea why such a popular bundle would do that, but it is what it is.
Your query as written checks for a user with specific id, and role. but you never provide the id or role!.
I dont think you want to query by id, so the correct query should be something like this:
public function listFitters(Request $request)
{
// Get Entity manager and repository
$em= $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
//set required role
$role = 'ROLE_FITTER';
$qb->select('u')
->from('userBundle:User', 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"' . $role . '"%');
$user = $qb->getQuery()->getResult();
// Serialize into an array the data that we need, in this case only name and id
$responseArray = array();
foreach ($users as $user) {
$responseArray[] = array(
"id" => $user->getId(),
"name" => $user->getName()
);
}
// Return array for dropdown
return new JsonResponse($responseArray);
}
Probably you should only select the fields you want (id, name) and avoid the array building loop, but i am not particularly familiar with symfony / doctrine so not sure of the correct syntax

How to delete user without posts in Laravel?

I'm working on L5.5 and I need to delete user but not his/her posts. So I basically need to assign his/her posts to another user which has to be Non-removable.
What I need:
Create a user which can't be deleted at least not from front-end even by owner of website but can be edited. (mostly is like bot for this application)
If I delete a user and that user had post(s) those post(s) remain and assign to this user (bot). It means this bot will become author of those posts.
Check for number 2 that only if user with post that happens if user has no post just delete him/her.
This is my usecontroller destroy method currently:
public function destroy($id)
{
$user = User::findOrFail($id);
Storage::delete($user->image);
$user->delete();
return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');
}
Thanks.
According to your needs, you will require softDeletes in your User model and their respective tables in the database, now this solves your 1st problem where your not deleting the user from table simply adding deleted_at column.
Edit: As you are using Zizaco\Entrust\Traits\EntrustUserTrait you need to have your user model look something like this:
class User extends Model implements AuthenticatableInterface
{
use Authenticatable;
use EntrustUserTrait { restore as private restoreA; }
use SoftDeletes { restore as private restoreB; }
public function restore()
{
$this->restoreA();
$this->restoreB();
}
}
For more information about this error you need to look: https://github.com/Zizaco/entrust/issues/742
so now coming to the 2nd point, retrieving the post with deleted model can be used withTrashed() something like:
$user = User::withTrashed()->all();
$user = User::withTrashed()->where('id', 1);
$posts = $user->posts()->get();
// Or do your relational things
Even if you want to assign it to different user then you need to create a new user and apply update methods to all the relational model while deleting the user which seems a bad idea.
Edit:
So in this case you can have:
$oldUser = User::find($id);
$user = User::find($botID); // Find the bot user
$oldFoods = $oldUser->food()->get();
foreach($oldFoods as $food)
{
$food->user_id = $user->id;
$food->save();
}
Now for your 3rd point if the user has no post then you can do a small check something like this:
$user = User::find($request->id);
$posts = $user->posts()->get()->first();
if(isset($posts))
{
$user->delete();
}
else
{
$user->forceDelete();
}
Hope this justifies all your needs.
Conclusion So fnally you can have your destroy method in userController as:
public function destroy($id)
{
$user = User::findOrFail($id);
$foods = $user->food()->get();
if(isset($foods))
{
$botUser = User::where('username', '=', 'bot'); // Find the bot user
foreach($foods as $food)
{
$food->user_id = $botUser->id;
$food->save();
}
$user->delete();
}
else
{
$user->forceDelete();
}
Storage::delete($user->image);
return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');
}
Edit your database with
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');

Yii2 eager loading not working

I have two entities in my database which are related by a one to many relationship: "User" and "Ad"
I have generated model classes using gii.
This is what I have in my model class for User:
public function getAds()
{
return $this->hasMany(Ad::className(), ['user' => 'id']);
}
and for my Ad model:
public function getUser0()
{
return $this->hasOne(User::className(), ['id' => 'user']);
}
according to Yii2 documentation, In the controller when I do
$ads = Ad::find()->all();
var_dump($ads[0]->user);
It should eagerly load user data from the DB but I only get the foreign key (1).
Even when I try
$ads = Ad::find()->with('user0')->all();
var_dump($ads[0]->user);
Its still the same.
thanks. If I want to send Ads and their related user data by xml in an ActiveController, do I have to do something like this:
$t = array();
foreach ($ads as $ad) {
$t[] = [$ad, $ad->user0];
}
return $t;
Or there is a more straightforward way to do that?
You are still getting Ad objects either with or without eager loading.
The difference is how the relations are populated, with lazy loading the relations are only loaded when they are accessed.
$ads = Ad::find()->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // query to load user record here
}
With eager loading they are populated up front.
$ads = Ad::find()->with('user0')->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // user0 already populated, no query
}
Probably You need joinWith
$ads = Ad::find()->joinWith('user0')->all();

Laravel 4: Updating table Joins with form model binding

I once did an eager loading query and it worked. Then using model binding i'm trying to update my two tables at once with no lucky. No error thrown, all validations are fine and when i tried to var_dump to see the values after validation , they are all there. I just can't get a way to update two tables in database using eloquent at a time. Please help.
Here is what i did so far:
ProfilesController.php
public function update($username)
{
$user = $this->getUserByUsername($username);
$input = Input::all();
try {
$this->profileForm->validate($input);
// dd($input);
$user->profile->update($input);
} catch (FormValidationException $e) {
return Redirect::back()->withInput()->withErrors($e->getErrors())->with('form_error', 'Sorry, we can not update your profile. Try again!');
}
return Redirect::route('profile.edit', $user->username)->with('form-success', 'Profile has been successfully updated!');
}
public function getUserByUsername($username)
{
return User::with('profile')->whereUsername($username)->firstOrFail();
}
Other files can be found here: http://laravel.io/bin/8eJK5

Categories