I have few $request->user->load() relationships :
Route::middleware(['auth:api','request.log'])->get('/user', function (Request $request) {
return $request->user()->load('accesses');
});
Route::get('settings', function (Request $request) {
return $request->user()->load('settings');
});
Route::get('logs', function (Request $request) {
return $request->user()->load('logs');
});
But for some reason, first relationship('accesses') don't work properly. I call this route right after user login to get user info and his accesses to different site modules. It returns user info correctly, but accesses is always null. Also, $this->id don't work inside model for this relation, while works for others. How can I fix it?
Relationship with problem
public function accesses()
{
if (!($this->hasOne(UserAccesses::class)->exists())) {
$accesses = new UserAccesses();
$accesses->user_id = Auth::id(); // $this->id don't work for some reason
$accesses->disk = true;
$accesses->mail = true;
$accesses->calendar = true;
$accesses->photos = true;
$accesses->contacts = true;
$accesses->save();
}
return $this->hasOne(UserAccesses::class);
}
almost the same relationship that works ok
public function settings()
{
if (!($this->hasOne(UserSettings::class)->exists())) {
$settings = new UserSettings();
$settings->user_id = $this->id;
$settings->backup_password = '';
$settings->backup_email = '';
$settings->codeword = '';
$settings->security_notifications = 0;
$settings->password_changed_at = null;
$settings->two_step_authentication = 0;
$settings->save();
}
return $this->hasOne(UserSettings::class);
}
Related
I have 4 table : Users, CompanyRegister, VoucherDetails, Addvoucher.
So the Authenticate Users Id will be submit as user_id in companyRegister table,and then companyRegister ID will be submit as company_id in Voucherdetails table, and lastly voucherDetails Id will be submit in addVoucher table as voucher_ID. I am new to using eloquent and also laravel, I cant understand why I cant get the id from voucherdetails and submit in addvoucher but I can get id from companyregister and submit in company_id in voucherdetails. I'm using the same method to get id but not work, I hope can get solution and explanation here,Thank you in advance!!
My users model
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
public function addvoucher()
{
return $this->hasMany('App\addvoucher');
}
public function roles()
{
return $this->belongsToMany('App\role');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
my companyregister model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
my voucherdetails model
public function User(){
return $this->belongsTo('User');
}
public function companyregisters(){
return $this->belongsTo('App\companyregisters');
}
public function addvoucher()
{
return $this->hasOne('App\addvoucher');
}
my addvoucher model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails(){
return $this->belongsTo('App\voucherdetails');
}
my voucherdetailsController
public function store(Request $request){
$voucherdetail = new voucherdetails();
$voucherdetail->title = $request->input('title');
$voucherdetail->description = $request->input('description');
$voucherdetail->user_id = Auth::user()->id;
$id = Auth::user()->id;
$user = User::find($id);
$company = $user->companyregisters;
$companyId = $company->id;
$voucherdetail->company_id = $companyId;
$voucherdetail->save();
return redirect()->to('addvoucher');
}
my addvoucherController
public function store(Request $request){
$addvoucher = new addvoucher();
$addvoucher->voucherTitle = $request->input('voucherTitle');
$addvoucher->voucherCode = $request->input('voucherCode');
$addvoucher->user_id = Auth::user()->id;
//Here(the voucherdetails id cant get to submit in voucher_id)
$id = Auth::user()->id;
$user = User::find($id);
$voucher = $user->voucherdetails;
$voucherID = $voucher->id;
$addvoucher->voucher_id = $voucherID;
$addvoucher->save();
return redirect()->to('displayVouchers');
}
This code works because companyregisters is a hasOne relationship for which the docs say:
Once the relationship is defined, we may retrieve the related record
using Eloquent's dynamic properties.
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
$company = $user->companyregisters; // ie this returns the single related record
$companyId = $company->id; // and it has an `id` property, all good here
However, this code fails because voucherdetails is a hasMany relationship for which the docs say:
Once the relationship has been defined, we can access the "collection"
of comments by accessing the comments property.
More info on collections
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
$voucher = $user->voucherdetails; // ie this returns a "collection" of related records
$voucherID = $voucher->id; // this "collection" does NOT have an id property, but each record IN the collection does.
In summary, either your relationship is defined incorrectly (hasMany vs hasOne) or, you'll need to loop over the related records to get the id from each.
I'm having a controller with some functions. In every function I get user data by sharing it from the Contoller.php
In controller.php
public function share_user_data() {
$user = Auth::user();
$this->checkValidation($user);
$this->user = $user;
View::share('user', $user);
}
public function checkValidation($user){
if($user->email_activated == 0){
var_dump($user->email_activated); // I get: int(0)
return redirect('/verifyEmail');
}
}
In the other controller
public function viewCategory(Category $category){
$this->share_user_data(); // here's the check
$this->get_site_lang();
$products = $category->products;
return view('category', compact('category','products'));
}
But I get the category view and not redirected to the verifyEmail route. How to fix this and why it's happening?
The controller function called by the route is the one responsible for the response. I guess it is viewCategory() in your example?
Your viewCategory() function is always returning view(). It must return redirect() instead. I think the main function should be responsible for picking the output of the request.
private function checkValidation($user) {
return $user->email_activated == 0;
}
public function viewCategory(Category $category) {
$user = Auth::user();
/* ... call to share_user_data() or whatever ... */
if ($this->checkValidation($user)) {
return redirect('/verifyEmail');
}
return view('category', compact('category','products'));
}
there.
So, I'm making a section for My reports, and I need to get the reports, from the database, based on id of logged user. How can I make that in my controller? I'm using \App\Reports::get(), but I need to get it based on the id of logging user, which is saved in database at user_id.
public function myReports($page = null)
{
if ($user = Sentinel::check())
{
// return $user;
$data = $this->data;
$id = $user->id;
$data['title'] = "My Reports";
$reports = \App\Reports::get();
$data['leftside_profile'] = 'my-reports';
$find_contact[] = $id;
// DB::enableQueryLog();
$page = Input::get('page');
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
{
$query->whereIn('user_id',$find_contact)
->where('type', '=', 'profile_updates');
});
return view('profile.my_reports',$data)
->with(compact('reports'));
}
else{
return redirect('home');
}
}
Reports model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Reports extends Model
{
protected $table = 'reports';
// public $timestamps = false;
protected $fillable = [
'user_id', 'username', 'user_id_posted', 'username_posted', 'news_id','opinion_id','event_id','career_solution_id', 'subject', 'why_reporting','why_reporting_message','additional_message','private'
];
public function career_solutionReport()
{
return $this->belongsTo('App\CareerSolution','career_solution_id','id');
}
public function eventReport()
{
return $this->belongsTo('App\Event','event_id','id');
}
public function newsReport()
{
return $this->belongsTo('App\News','news_id','id');
}
public function opinionReport()
{
return $this->belongsTo('App\Opinion','opinion_id','id');
}
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
}
If the user is logged in you can call Sentinel::getUser()->id to retrieve the user id.
Change
$reports = \App\Reports::get();
To
$reports = \App\Reports::where('user_id', Sentinel::getUser()->id)->get();
I have a many to many relation between the tables user and clinic and the third table is user_clinics. All three tables returns their values perfectly individually, but when i call App\User::find(1)->clinics or its inverse it returns null. Moreover, user_clinic has user_id and clinic_id and also previlage_id as a foreign key.
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
public function adminDashboard(Request $request) {
$clinic = new Clinic();
$User_clinic = new User_clinic();
$user = new User();
$clinic->name = $request->name;
$clinic->address = $request->address;
if($request->hasFile('logo')) {
$fileName = $request->logo->getClientOriginalName();
$request->logo->storeAs('public/logos',$fileName);
$clinic->logo = $request->logo;
}
$clinic->save();
$User_clinic->user_id = auth::user()->id;
$test=$User_clinic->clinic_id = $clinic->id;
//now hardcoded previlage_id but deal with it in future...
$User_clinic->previlage_id = 1;
$User_clinic->save();
$test= $clinic::find(2)->users;
dd($test);
//return view("admin.dashboard.dashboardFirstPage");
}
Your relationship is not quiet right:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
It should be like below:
In User model:
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','user_id','clinic_id');
}
In Clinic model:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','clinic_id','user_id');
}
I'm trying to create a callback to return my views based on data from my current logged-in user. If I do something basic like echoing 'hi' it works, is there any way accomplish this?
function checkUser($type,$callback){
if( is_callable($callback) ){
call_user_func($callback);
}
}
class FichaController extends Controller
{
public function contarFichas()
{
checkUser('particular',function(){
$currentUser = Auth::user();
$countFichas = Ficha::where('user_id',$currentUser->id)->count();
return view('particular.index', array('countFichas' => $countFichas));
});
}
}
Return the result from checkUser
if( is_callable($callback) ){
return $callback();
}
public function contarFichas()
{
return checkUser('particular',function(){
$currentUser = Auth::user();
$countFichas = Ficha::where('user_id',$currentUser->id)->count();
return view('particular.index', array('countFichas' => $countFichas));
});
}