I'd like to be able to modify the Auth->user() data that Laravel 5.6 uses. I have table called settings with a column called user_id in it that corresponds to a user id.
I tried modifying app\User.php and adding a __construct function:
public function __construct() {
$this->settings = Settings::where('user_id',
Auth->user->id()
)->first();
}
And I created a file app\Settings.php with the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class settings extends Model
{
protected $table = "settings";
}
However I'm getting a user error on the Auth->user()->id line in User.php, although I'm sure thats the correct way to reference it?
How can I load the data from the settings table to the User class?
You can just use load() method to lazy load the relation:
auth()->user()->load('settings');
You need to do this just once per request, in a middleware for example. Then you'll be able to use the data in any part of your app:
{{ auth()->user()->settings->theme }}
Of course, to make this work you need to define relationship in the User model, for example:
public function settings()
{
return $this->hasOne(Settings::class);
}
Related
I'm having some issues using Voyager. I can create Accessors to attributes, as described in the documentation. It works nicely to access the data, but I also have to create a Mutator to change the data before saving it. Apparently, there's no implementation by Voyager, so I tried to do it through Laravel way. It also works very nicely in common environments, but for some reason, there is a different behavior with Voyager.
The Mutator is called after the Accessor, even when only browsing:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
public function setNameAttribute($value){ // my mutator
$value = preg_replace("/[^a-zA-Z]/", '', $value);
$this->attributes['name'] = $value;
}
public function getNameBrowseAttribute(){ // my accessor
return $this->name . '...'; // example
}
}
What is happening:
When I access the browser of my Model, the getNameBrowseAttribute is called, as it should be, but after that, the setNameAttribute is called as well, which should not happen because I'm browsing, and not saving or updating the Model.
I tried to debug the code, and the last Voyager file called is a view, from voyager/storage/framework/views/, where $data is the Model:
if ($data->{$row->field.'_browse'}) {
$data->{$row->field} = $data->{$row->field.'_browse'}; // <-- this line
}
As you can see, it is calling a method with ...browse, and not set...
Any help is appreciated :)
You could try to do with model events. Use the saving event.
https://laravel.com/docs/8.x/eloquent#events
I'm currently trying to use Laravel Relationships to access my achievements Model using User model, I use this relationship code:
public function achievements()
{
return $this->hasMany('App\Models\User\Achievement');
}
I can easily make some eloquent queries, however I can't access any method that I created there, I can't access this method:
class Achievement extends Model
{
public function achievementsAvailableToClaim(): int
{
// Not an eloquent query
}
}
Using the following code:
Auth::user()->achievements()->achievementsAvailableToClaim();
I believe that I am using this Laravel function in the wrong way, because of that I tried something else without using relationship:
public function achievements()
{
return new \App\Models\User\Achievement;
}
But that would have a performance problem, because would I be creating a new class instance every time I use the achievements function inside user model?
What would be the right way of what I'm trying to do?
it's not working because your eloquent relationship is a hasMany so it return a collection. you can not call the related model function from a collection.
you can var dump it on tinker to understand more what i mean.
You can use laravel scopes.Like local scopes allow you to define common sets of constraints that you may easily re-use throughout your application.
In your case you use this like, Define scope in model:
public function scopeAchievementsAvailableToClaim()
{
return $query->where('achivement_avilable', true);
}
And you can use this like :
Auth::user()->achievements()->achievementsAvailableToClaim();
Heey guys! I use Laravel 5.4, WAMP for localhost. I am struggling with the problem to call a Controller#methodName within my header.blade.php file, because I want to show in my header.blade.php file all notifications for the User. Normally I was getting all needed data with the help of routes in different pages. But for this case I need to call without using routes. Here is my code for my NotificationController:
class NotificationController extends Controller
{
public function getNotification(){
$notifications = Notification::where('user_id',Auth::user()->id)->get();
$unread=0;
foreach($notifications as $notify){
if($notify->seen==0)$unread++;
}
return ['notifications'=>$notifications, 'unread'=>$unread];
}
}
And I should receive all these data in my header file. I have used: {{App::make("NotificationController")->getNotification()}}
and {{NotificationController::getNotification() }} But it says Class NotificationController does not exist. Please heelp!
Instead of calling the controller method to get notifications, you can make a relationship method in your User model to retrieve all the notifications that belongs to the user and can use Auth::user()->notifications. For example:
// In User Model
public function notifications()
{
// Import Notification Model at the top, i.e:
// use App\Notification;
return $this->hasMany(Notification::class)
}
In your view you can now use something like this:
#foreach(auth()->user()->notifications as $notification)
// ...
#endforeach
Regarding your current problem, you need to use fully qualified namespace to make the controller instance, for example:
app(App\Http\Controllers\NotificationController::class)->getNotification()
Try using the full namespace:
For instance, App\Http\Controllers\NotificationController::getNotification
but of course, controllers aren't meant to be called the way you're using them. They're meant for routes. The better solution is to add a relationship in your user model like so:
public function notifications()
{
return $this->hasMany(Notification::class)
}
And then use this in your view like so:
#foreach(Auth::user()->notifications as $notification)
I'm trying to retrieve data from a table called completion_date using Eloquent. My Model name is Completion and as per laravel documentation, i should declare a (protected) table name or else Eloquent will use 'completions' as the default table name. So i did this declaration.
I'm getting problems with my Controller since i dont know which name to use to refer to my Model when i'm making the View. I'm getting an InvalidArgumentException that View [completion.lsz] not found. if i just use my model name to make the View.
Error:
InvalidArgumentException thrown with message "View [completion.lsz] not found."
Can someone pls help out?
Model
<?php
//Model (file name: Completion)
class Completion extends Eloquent{
protected $table = 'completion_date';
public $timestamps = false;
}
Controller
class CompletionController extends BaseController {
public function index() {
$lsz = Completion::all();
return View::make('completion.lsz', ['completion' => $lsz]);
}
}
Route
Route::get('/Completion', 'CompletionController#index');
View names in Laravel work like a path. The . gets converted to a /
That means, your view resolves to the file app/views/completion/lsz.blade.php (or app/views/completion/lsz.php without Blade)
So you either have to change the name of your directory in the views folder to "completion" or change the view make command to:
View::make('lsz.lsz', ['completion' => $lsz]);
The error message says that the view file completion/lsz.blade.php was not found.
It's not related to the model or database.
I created a User class in Laravel application as follows:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
...
public function hasAnyRoles()
{
return true;
}
The function there is simplified to always return true for the purposes of this example. I pretty much followed this tutorial here to create this class: http://alexsears.com/article/adding-roles-to-laravel-users. I created a controller next as follows:
class WelcomeController extends Controller
{
public function welcomeAction()
{
$user = User::find(Auth::user()->id);
$result = $user->hasAnyRoles();
return Response::make("Result: ".$result);
}
}
I'm able to successfully login to the system, routes are working as intended, the variable $user is correctly initialized and I can get all the information out of it (username, id, email, etc.) but once I call the $user->hasAnyRoles() method I get:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::hasAnyRoles()
If I comment out the respective line in the controller it all works but I cannot call any method of that model without getting that error. Any ideas why this is happening?
As stupid as it is, it turns out that the application was reading the User class from a different file. I had a User_backup.php copied in the same directory just in case and this was the file that the class was read from so any changes to User.php were disregarded. I had to remove the backup file and do a composer update in order to get it all working correctly..