Laravel 4 - Access Auth Class in Validation Class - php

I want to access the Auth Class within my ValidatorService Class.
namespace Services\Validators\User;
use \Services\Validators\Validator;
use \Illuminate\Support\Facades\Auth;
class Edit extends Validator {
public static $rules = [
'email' => 'required|unique:users,email,'.Auth::user()->id
];
}
I tried to use the \Illuminate\Support\Facades\Auth Namespace, but laravel throws an Exception.
Error: syntax error, unexpected '.', expecting ']'
Laravel only throws the exception, when I try to use Auth::user()->id.
If I remove Auth::user()->id and add a number, for example 1, it works.
I also tried to implement the Illuminate\Auth\UserInterface but it is not working.
How can I use the Auth Class in my ValidatorService Class?
EDIT: Problem solved -> Scroll down.

Solution:
You cannot use functions or variables when setting a variable on a
class.
Thanks to AndreasLutro on http://laravel.io/irc
So I removed the class variable and added a method.
Now everythings works fine.
Code:
class Edit extends Validator{
public static function rules(){
return array(
'email' => 'required|unique:users,email,'.Auth::user()->id
);
}
}
Cheers, Steven.

Try to surround the 'required|unique:users,email,'.Auth::user()->id
part with ( and ) so that it looks like this:
public static $rules = [
'email' => ('required|unique:users,email,' . Auth::user()->id)
];

Related

Error with Invoke type controller in Laravel

I'm having problems with and invoke type controller.
After I create the controller with php artisan make:controller -i and add the route, when go to the route it tells me that the Invoke function doesn't exist.
Here is the route I'm using:
Route::get('/portfolio','PortfolioController');
And here is the code of the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PortfolioController extends Controller
{
public function __invoke(Request $request)
{
/** #var array $portafolio */
$portafolio = [
["title" => "Proyecto #1"],
["title" => "Proyecto #2"],
["title" => "Proyecto #3"],
["title" => "Proyecto #4"],
];
return view("portfolio", compact("portafolio"));
}
}
I don't really get why this error occurs, because the invoke function is clearly there, so if anyone knows what could be the problem I will be really grateful.
I'm using the last version of Laravel.
You need to use the fully qualified class name as in the documentation:
use App\Http\Controllers\PortfolioController;
Route::get('/portfolio', PortfolioController::class);

Laravel 5 Constant define

I tried all the options. Still, it is showing "Constant expression contains invalid operations". I am using Laravel 5.5, Please Help. I need to define table name in constant and use it in Model.
I wrote in Model:
protected $table = Config::get('constants.dbTable.EMAILTEMPLATE');
And In constant.php inside Config:
return [ 'langs' =>
[
'es' => 'www.domain.es',
'en' => 'www.domain.us' // etc
],
'siteTitle' => 'HD Site',
'pagination' => 5,
'tagLine' => 'Do the best',
'dbTable'=>[
'EMAILTEMPLATE' => 'stmd_emailTemplate'
]
];
I want to use emailTemplate table.
Based on the code you have posted in the comment, you are trying to assign a value into a property in your model but you are assigning it too early (assumed from the keyword protected.) You can't do this:
class SomeModel extends Model
{
protected $someProperty = config('some.value'); // Too early!
}
because you are trying to initialize a property that requires a run-time interpretation.
There's a workaround; use your constructor.
class SomeModel extends Model
{
protected $someProperty; // Define only...
public function __construct() {
parent::__construct(); // Don't forget this, you'll never know what's being done in the constructor of the parent class you extended
$this->someProperty = config('some.value');
}
}

Yii2 REST Simplify BasicAuth

I'm impressed with how simple it was to create a REST api in Yii2. However, i'm having a little trouble understanding the Basic Authentication. My needs are utterly simple and i'd like my solution to follow suit.
I need Basic token authentication here. I'm not even against hardcoding it for now, but here's what i've done thus far.
I have database table to hold my singular token ApiAccess(id, access_token)
ApiAccess.php - Model - NOTE: IDE shows syntax error on this first line
class ApiAccess extends base\ApiAccessBase implements IdentityInterface
{
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
}
Module.php - in init() function
\Yii::$app->user->enableSession = false;
I made an ApiController that each subsequent noun extends
ApiController.php
use yii\rest\ActiveController;
use yii\filters\auth\HttpBasicAuth;
use app\models\db\ApiAccess;
class ApiController extends ActiveController
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
}
As it stands, accessing an api endpoint in the browser prompts for a username and password. Request via REST Client displays access error.
How do I properly tie HttpBasicAuth to my ApiAccess model?
OR
How do I hardcode an api access token? (First option is obviously best)
Let's watch and try to understand "yii" way basic auth for REST.
1st. When you adding behavior to your REST controller, you enabling basic auth:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
As you did. What does it mean? It means that your application will parse your authorization header. It looks like:
Authorization : Basic base64(user:password)
Here is a trick for yii2. If you look at code more carefully, you will see that yii uses access_token from user field, so your header should look like:
Authorization : Basic base64(access_token:)
You can parse this header by your own, if you want to change this behavior:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
....
public function auth($username, $password)
{
return \app\models\User::findOne(['login' => $username, 'password' => $password]);
}
2nd thing to do. You must implement findIdentityByAccessToken() function from identityInterface.
Why your IDE complaining?
class User extends ActiveRecord implements IdentityInterface
Here's how your user class declaration should look.
From your implementation and structure:
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
you not returning object of class which implements identity interface.
How to make it properly?
Add column access_token to your users table, and return back your user model (you can look how it must look here - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php)
If you do this - default code will work with your findIdentityByAccessToken() implementation.
If you don't want to add field to users table - make new one with user_id,access_token fields. Then your implementation should look like:
public static function findIdentityByAccessToken($token, $type = null)
{
$apiUser = ApiAccess::find()
->where(['access_token' => $token])
->one();
return static::findOne(['id' => $apiUser->user_id, 'status' => self::STATUS_ACTIVE]);
}
Hope i could cover all of your questions.

Laravel Twitter Library - Where is the static function getUserTimeline()

I'm new in Laravel, I'm trying to understand how it works. I have setup this library as defined.
https://github.com/thujohn/twitter-l4
Examples works perfect when I define use with only Twitter; Shown below
use Stream;
use Twitter;
class GoController extends \BaseController{
function go($id){
return Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}
but it throws this error when I use Thujohn\Twitter\Twitter;
use Stream;
use Thujohn\Twitter\Twitter;
class GoController extends \BaseController{
function go($id){
return Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}
Non-static method Thujohn\Twitter\Twitter::getUserTimeline() should
not be called statically, assuming $this from incompatible context
So, I'm unable to understand why I can't use the second form?
Beacuse in the second example you're using the class directly, which happens to have the same name as the alias accessor.
What you see called statically is a Façade, which actually instantiates the class by using a static method (I'm not really good at explaining things...)
If you followed the instructions you should have created an Alias in the config/app.php file.
'Twitter' => 'Thujohn\Twitter\TwitterFacade',
And this alias is the very Twitter class (i.e., the façade) you need to call, and that you see called in the documentation.
So, remove the use statement use Thujohn\Twitter\Twitter; and your code will be using the "Twitter" alias (like it did in the first example), i.e. will call the Facade accessor.
use Stream;
class GoController extends \BaseController
{
public function go($id)
{
return \Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}

Call a custom model method from controller laravel4

I have a model like this:
class Event extends Eloquent
{
protected $softDelete = true;
public function scopeSearchEvents($search_criteria)
{
return Event::whereIn('title',$search_criteria)
->orWhereIn('description',$search_criteria)
->whereApproved('1')
->orderBy('event_date','desc')
->get();
}
}
And im calling it from the controller like this:
$data = Event::search($search_criteria);
But it gives this error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to undefined method Illuminate\Events\Dispatcher::search()
What is the best way of calling a custom model method from your controller?
Make changes to your method as given below:
public function scopeSearchEvents($query, $search_criteria)
{
return $query->whereIn('title', $search_criteria)
->orWhereIn('description', $search_criteria)
->whereApproved('1')
->orderBy('event_date','desc');
}
Then call it like searchEvents not search:
// Don't use Event as your model name
$data = YourModel::searchEvents($search_criteria)->get();
Also make sure that, you want to use whereIn instead of where('title', 'LIKE', "% $search_criteria") and so.
Update:
You should change the model name from Event to anything else because Laravel has it's core Event class, actually a Facade which is mapped to 'Illuminate\Support\Facades\Event'.
Have a look at the app.php:
'aliases' => array(
...
'Event'=> 'Illuminate\Support\Facades\Event',
...
);
"Event" is defined as an alias. That's why your Event calls "Illuminate\Support\Facades\Event".
Now if you want to use your event model without typing the namespace to call methods create an alias like:
'MyEvent' => 'App\Models\Event',
and then:
MyEvent::create();

Categories