I'm using laravel 5.4, in my User.php file I want to write a function like this :
public function isAdmin(Request $request)
{
if ($request->user()->id == 1) {
return true;
}
}
The function I want to use in my middleware and my blade file. How to write this ?
Now it's giving me this error :
Type error: Argument 1 passed to App\User::isAdmin() must be an
instance of Illuminate\Http\Request, none given, called in
/home/mohib/MEGA/Projects/saifullah-website/app/Http/Middleware/isAdmin.php
on line 18
If you want to find out if the currently authenticated user is an Administrator, based on your logic, you could do something like this:
In App\User.php
public function isAdmin()
{
if ($this->id == 1)
{
return true;
}
return false;
}
and then, you can use it like this:
if(Auth::check() && Auth::user()->isAdmin())
{
// do something here
}
Related
I am trying to add a custom Behavior that is a clone of the default Timestamp. Mine is "Userstamp" adding the current user to audit-trail fields on all tables. At the point where Timestamp sets the field to "new FrozenTime($ts)", I want to set to "$identity->get('username')" or similar. I am having trouble reaching anything from Authentication/Authorization or Identity from within the Behavior.
I know that the information is there, somewhere. But what do I need to include in my Behavior class in order to retrieve it?
I found this link, but I don't see where to put the suggested code.
In my Table:
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('Userstamp');
.
.
.
}
Cake's timestamp Behavior:
public function timestamp(?DateTimeInterface $ts = null, bool $refreshTimestamp = false): DateTimeInterface
{
if ($ts) {
if ($this->_config['refreshTimestamp']) {
$this->_config['refreshTimestamp'] = false;
}
$this->_ts = new FrozenTime($ts);
} elseif ($this->_ts === null || $refreshTimestamp) {
$this->_ts = new FrozenTime();
}
return $this->_ts;
}
My userstamp Behavior:
public function userstamp($userstamp = null, bool $refreshUserstamp = false)
{
// Variations of this do not work, the Property is not available in UserstampBehavior
// $currentUser = $this->Authentication
// ->getIdentity()
// ->getIdentifier();
$currentUser = 'abc'; <<<<<<<<<<<<< Hard-coded temporarily
if ($userstamp) {
if ($this->_config['refreshUserstamp']) {
$this->_config['refreshUserstamp'] = false;
}
$this->_userstamp = $currentUser;
} elseif ($this->_userstamp === null || $refreshUserstamp) {
$this->_userstamp = $currentUser;
}
return $this->_userstamp;
}
Your Auth-Informations lives also in the session.
So you can access Session-stuff in a table-class like this:
(new Session)->read('Auth')
And therefore you give this information from a table-class to your Behaviour like this:
$this->addBehavior('Userstamp', ['user_info'=>(new Session)->read('Auth')]);
Then you can access this information in your behaviour:
public function initialize(array $config){
$this->user_info = $config['user_info'];
}
public function myFunction(){
// do something with $this->user_info
}
I have a set of get functions in JS such as:
get UserName() {
return this.userModel.Name;
}
I want the ability to check if the function exist before I call it.
I tried:
if (this.UserName == 'function')...
but it's always false, since userModel.name is a string, typeof UserName returns 'string' type and not a 'function'.
any idea how I can accomplish this ?
One simple way to check that UserName exists (without calling the getter) is to use in:
if ('UserName' in this) {
// this.UserName is defined
}
If you need a stronger check where you directly access the getter function, use Object.getOwnPropertyDescriptor:
var userNameDesc = Object.getOwnPropertyDescriptor(this, 'UserName');
if (userNameDesc && userNameDesc.get) {
// this.UserName is definitely a getter and is defined
}
You can use Object.getOwnPropertyDescriptor() which returns basically the same data structure that is fed to Object.defineProperty() like this:
let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (descriptor && typeof descriptor.get === "function") {
// this.UserName is a getter function
}
Or, if you want more granular info, you can do this:
let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (!descriptor) {
// property doesn't exist
} else if (typeof descriptor.get === "function") {
// this.UserName is a getter function
} else if (typeof descriptor.value === "function") {
// property directly contains a function (that is just a regular function)
} else {
// property exists, but it does not have a getter function and
// is not a regular function
}
You can also test many other properties of the descriptor such as value, set, writable, configurable, enumerable as described here on MDN.
I need to build a query with eloquent model including conditional where clause. I created something by searching google. But it doesn't seems to be working.
if ($status) {
$this->where('status', $status);
}
if ($assignedto) {
$this->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$this->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $this->orderBy('date', 'desc')->paginate(40);
This one returns all results without the filtering of status, assigned to and dates.
I just updated it by assigning $this to a new variable because when I assigned the query to $this, it shown an error, $this cannot be over written.
$quoteModel = $this;
if ($status) {
$quoteModel = $quoteModel->where('status', $status);
}
if ($assignedto) {
$quoteModel = $quoteModel->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$quoteModel = $quoteModel->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $quoteModel->orderBy('date', 'desc')->paginate(40);
which works perfectly now. But if somebody have some better option, please suggest. Thanks.
I added a scope to my model and call it from the controller. This way the actual filtering work is done in the model, the controller is just running the query through the filter scope.
Model:
I am getting URL parameters with Input::get, but you would also pass them as input parameters to the function.
public function scopeFilter($query)
{
$published = Input::get('published');
if (isset($published)) $query->where('published', '=', $published);
return $query;
}
Controller:
Here the query is run through the filter() before returning it to the view.
public function index()
{
return View::make('articles.index', [
'articles' => Article::with('writer')->filter()->get()
]);
}
I currently have some code from here (https://github.com/jmhnilbog/Nilbog-Lib-AS2/blob/master/mx/mx/remoting/NetServiceProxy.as) which converts a function into a function. This code is shown below:
private var _allowRes:Boolean= false;
function __resolve( methodName:String ):Function {
if( _allowRes ) {
var f = function() :Object {
// did the user give a default client when he created this NetServiceProxy?
if (this.client != null) {
// Yes. Let's create a responder object.
arguments.unshift(new NetServiceProxyResponder(this, methodName));
}
else {
if (typeof(arguments[0].onResult) != "function") {
mx.remoting.NetServices.trace("NetServices", "warning", 3, "There is no defaultResponder, and no responder was given in call to " + methodName);
arguments.unshift(new NetServiceProxyResponder(this, methodName));
}
}
if(typeof(this.serviceName) == "function")
this.serviceName = this.servicename;
arguments.unshift(this.serviceName + "." + methodName);
return( this.nc.call.apply(this.nc, arguments));
};
return f;
}
else {
return null;
}
}
Basically what the code is designed to do is return a new function (returned as f) which performs the correct server operates. However, if I try and use this syntax in AS3, I get the following two errors:
Error: Syntax error: expecting semicolon before colon.
Error: Syntax error: else is unexpected.
How would I go about doing this? I know this is someone else's code, but I am trying to get the old AS1/2 mx.remoting functionality working in AS3. Cheers.
I've come across some syntax I'm not familiar with and am unable to find any reference online.
In the below as3 function is the if statement calling the 'sendTrackingEvent' function? And in the 'sendTrackingEvent' function is the if statement sending the tracking event?
function trackingHandler(page: String)
{
if (! sendTrackingEvent(EID,"Document View",page))
{
fl_SavePreferences_5(EID + ",Document View," + page);
}
}
function sendTrackingEvent(category:String, action:String, label:String):Boolean
{
if (tracker.trackEvent(category,action,label))
{
return true;
}
else
{
return false;
}
}
Thanks in advance for any help. I'm still learning.
sendTrackingEvent is a function that returns true or false
the first if statement is evaluating the RESPONSE (return value) of that function. So if sendTrackingEvent(EID,"Document View",page) returns false, then your if statement will run (since the ! means NOT true).
Same for the second if statement inside of sendTrackingEvent.
It's evaluating the return value of tracker.trackEvent(category,action,label).
That function (sendTrackingEvent) could actually be simplified to this:
function sendTrackingEvent(category:String, action:String, label:String):Boolean
{
return tracker.trackEvent(category,action,label);
}
And for that matter you don't even need the sendTrackingEvent function, as you could just do this:
function trackingHandler(page: String)
{
if (! tracker.trackEvent(EID,"Document View",page))
{
fl_SavePreferences_5(EID + ",Document View," + page);
}
}