I created an artisan custom command and in the handle() method i need to get a few info about users.
When i run:
handle() {
$users = User::all();
foreach($users as $user) {
$this->line($user->name);
}
}
it works, but i need something like:
handle() {
$users = User::all();
foreach($users as $user) {
$this->line($user->summoner->summoner_id);
}
}
And i get Trying to get property of non-object.
If i run the same code above in a controller it works just fine.
Does anyone have an idea?
User model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function summoner() {
return $this->hasOne('App\Summoner');
}
Summoner model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Summoner extends Model
{
protected $table = 'summoners';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
}
As #aynber metnioned above, if DB field user.summoner_id can be set to NULL, then there are users without related Summoner.
So you can use whereHas method of the QueryBuilder, which will check relationship summoner existence:
$users = User::whereHas('summoner')->get();
foreach($users as $user) {
$this->line($user->summoner->summoner_id);
}
Or you can check existens of the relationship summoner for every selected user, but this approach may select redundant data from DB (if you need all users with non-NULL summoner_id field):
$users = User::all();
foreach($users as $user) {
if(empty($user->summoner)){
continue;
}
$this->line($user->summoner->summoner_id);
}
You can find more information about whereHas method here:
Laravel 5.4, Querying Relationship Existence: https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
The only strange thing, that as you said (if I get you right), in non-artisan "regular" controller the same code executes without errors. Possible, it's just a coincidence: may be when you've checked your code in non-CLI (command line input) controller, all users had a summoner.
Related
I want to fetch data from database in table but it show me undefined variable error in view please help me to solve this problem
my controller
class showAttendanceController extends Controller
{
public function index()
{
$users=DB::select('select * from requests');
return view('showAttendance',compact('users'));
}
my view
#foreach ($users as $user)
<td>{{$user->date}}</td>
<td>{{$user->Name}}</td>
<td>{{$user->Misid}}</td>
<td>{{$user->semester}}</td>
<td>{{$user->Department}}</td>
<td>{{$user->section}}</td>
<td>{{$user->Attendance}}</td>
My Route
Route::get('/showrecord','showAttendanceController#index')->name('showrecord');
Controller:
public function index()
{
$users = DB::table('requests')->get();
return view('showAttendance',compact('users'));
}
View:
#foreach($users as $user)
<td>{{$user->date}}</td>
<td>{{$user->Name}}</td>
<td>{{$user->Misid}}</td>
<td>{{$user->semester}}</td>
<td>{{$user->Department}}</td>
<td>{{$user->section}}</td>
<td>{{$user->Attendance}}</td>
#endforeach
first of all, it's better to create your table using migrations in order to have Database Consistency.
Further try to use models to interact with Database
for example
namespace App;
use Illuminate\Database\Eloquent\Model;
class deposit extends Model
{
//
protected $keyType = 'string';
protected $table = "deposit";
protected $fillable = [
'uid', 'amount', 'title', 'description'
];
}
and then you can use it in your controller
$deposit = deposit::find($request->deposit_id);
if($deposit){
return $deposit
} else {
return 'Some Error'}
first of all you have to use DB in your controller
public function index()
{
$users = DB::table('table_name')->get();
return view('showAttendance',compact('users'));
}
than you have to confirm your return view file location is right or not.Exmple if your showAttendence file is inside a folder you have to use
return view('foldername.showAttendence',compact('users));
I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
I'm having an issue with soft delete. I have a feature in my app where a user can star a followed property advert. They can also unstar a property advert.
This works fine. when they unstar it, the record is soft delete. The delete_at timestamp is updated.
However, if the user tries to star it again, I get a message saying that the property has already been liked/starred. So the soft delete is being ignored? Any ideas?
StarredPropertyModel
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class StarredProperty extends Model
{
use SoftDeletes;
protected $fillable = ['property_id', 'user_id'];
public function scopeStarredProperty($query, $propertyId, $userId)
{
return $query->where('property_id', $propertyId)->where('user_id', $userId)->first();
}
}
StarredPropertyController
class StarredPropertyController extends Controller
{
public function star(Property $property, User $user, Request $request)
{
if(!$user->starredProperties()->starredProperty($property->id, $user->id))
{
return response()->json(StarredProperty::create(['property_id' => $property->id, 'user_id' => $user->id]));
}
return response()->json('You have already like this property');
}
public function unstar(Property $property, User $user, Request $request)
{
$starredProperty = $user->starredProperties()->starredProperty($property->id, $user->id);
if($starredProperty->exists())
{
$starredProperty->delete();
}
}
}
You are missing a ->get() at the end of the if that checks if starredProperty exists on the star function.
$user->starredProperties()->starredProperty($property->id, $user->id) returns a query, not a record. To get the record you still need to execute get, if there are no records then the value returned from get will be null.
Am new to laravel, I have issues trying to connect this tables: plans,users and loans even after reading the docs,
I have a plans tables that have all my plans, then I have a users table and loans table, my loans table has a user_id and a plan_id, all I want is to pull the records for plans and the users in the loan model.
Loanplan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
//
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->belongsTo('App\loan');
}
}
my loan model:
Loan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
I want get all the loan plans and users table records with plan_id and user_id as foreign respectively respectively in my LoanController.
I think the problem is with the customization of the loans table name in the Loanplan model.
According with your descriptions you need the followings setup:
A User can access to one or many Loans
users 1---m plans
A Loan belongs to a Loanplan // here I'm using Loanplan because that is your model name.
loans 1---m plans
So, this means:
User.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
Loan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
//
];
public function user()
{
return $this->belongsTo(User::class);
}
public function plan()
{
// Notice that here I'm specifying the foreign key:
return $this->belongsTo(Loanplan::class);
}
//
}
Loanplan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
So with this, you can access the information in your LoanController.php:
LoanController.php
public function myCoolMethod()
{
// get a user
$user = User::first();
// access his/her loans
$loans = user->loans;
//
// get a loan plan
$plan = Loanplan::first();
// access its loans
$loans = plan->loans;
//
}
I strongly suggest you to read the Laravel Documentation regarding relationships and also a course for database design. Have a good day mate.
Loanplan.php is missing the protected $table = "plans" variable
Same file,
public function loan()
{
return $this->belongsTo('App\loan');
}
the relationship should be hasOne or hasMany, not belongsTo.
Moreover, the name of the class should have Loan with capital L.
public function loan()
{
return $this->...('App\Loan');
}
First of all add protected $table = 'plans'; to your Loanplan model since the table name is 'plans'
Loanplan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->hasOne('App\loan'); // or hasMany
}
}
?>
Loan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
?>
add this to the User Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function Loan()
{
return $this->hasOne('App\Loan'); // or hasMany
}
}
?>
First, you have to check if the model already querying from table that you created before. Laravel will automatically access table base on your class name.
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
You can read it from this documentation
Second, make sure you call the right class. From Loanplan.php in the loan() method it's not using uppercase for the first letter.
Third, try to state the foreign key and primary key. You can also check how to do it in the documentation.
I wan't to get the name of the user who created is own thread. Like Michael did a thread about food. So at the bottom of the food-thread should be the name of Michael.
I've wrote the code for this but it doesn't really works. Maybe someone of you can find the mistake.
I have two models. A thread Model and a users model.
thread model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
'user_id'
];
public function userthread() {
return $this->belongsTo('User','user_id', 'id');
user model:
<?php
namespace App;
use ...
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function threaduser() {
return $this->hasMany('App\Models\Thread\Thread','user_id', 'id');
}
}
and now the controller method, where I'm trying to get the name:
public function show($id)
{
$thread = Thread::query()->findOrFail($id);
$threaduser = Thread::where('user_id', Auth::user()->id)->with('userthread')->get();
return view('test.show', [
'thread' => $thread,
'threaduser' => $threaduser
]);
}
in my html:
{{$threaduser->name}}
The error message I get is :
Undefined property: Illuminate\Database\Eloquent\Collection::$name (View: /var/www/laravel/logs/resources/views/test/show.blade.php)
I hope someone can help me there.
change it to
{{$threaduser->userthread->name}}
change userthread() function in your Thread Class to
public function userthread() {
return $this->belongsTo('App\User','user_id', 'id');
}
get() gives you a Collection not a Model you either have to do a foreach on it like
#foreach ($threadusers as $threaduser)
{{ $threaduser->userthread->name }}
#endforeach
Or use first instead of get if there is only one Thread per User.
Depending on what you want to do, of course.