anonymox

anonymox

Member Since 2 Years Ago

mashhad

Back-End developer at karafarinan boland avazeh

Experience Points 1,610
Experience Level 1

3,390 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 1
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

03 May
1 year ago

anonymox started a new conversation Authorization For Laravel Passport Through Socket.io For Broadcasting Channels

I'm using laravel 5.3 + passport for authorization, Laravel is my back-end API which is restful.

front-end is written in angular.js which communicate with API with rest requests.

For Real-time notifications, I've used laravel broadcasting events + redis, and socket.io for socket server and socket client in angular.js.

I want to authorize these events and I've done it far as I could :

BroadcastServiceProvider :

public function boot() { Broadcast::routes(['middleware' => ['auth:api']]); Broadcast::channel('App.User.*', function ($user, $userId) { return (int) $user->id === (int) $userId; });

Broadcast::channel('notifs.*', function ($user, $userId) { return $user->id === (int) $userId; }); }

This is my socket.js code which runs my socket server :

var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var Redis = require('ioredis'); var redis = new Redis();

redis.psubscribe('*', function(err, count) {});

redis.on('pmessage', function(subscribed, channel, message) { console.log(channel); message = JSON.parse(message); io.emit(channel + ':' + message.event, message.data); });

http.listen(3000, function () { console.log('Listening on Port 3000'); });

redis.on("error", function (err) { console.log(err); });

The problem is I don't know how to authenticate these broadcasting events in socket server and also how to authorize the user in angular.js (SPA) to listen to these events.

I'd appreciate any help.

25 Dec
2 years ago

anonymox left a reply on How To Add And Update Config Varaibles In Laravel

I've Found out that : The configuration files are read only files, I cannot add parameters to it programmatically.

$banners = config('Banners_size');

config('Banners_size' , $bannerinfo);

The above two lines, will act the same, and will both return the value of Banner_size.

anonymox started a new conversation How To Add And Update Config Varaibles In Laravel

I have a config variable file which I'm using it in my controllers instead of mysql for faster performance.

But my problem is that I can only read from this config file and I can not add or update any value from it.

any suggestion how to udpate or add new values to this variable file :

my variable file which is stored in /config/Banners_size.php:

return [
    "normal_x970h90" => [
        'status' => 'enable',
        'value' => '500'
    ],

    "normal_x234h60" => [
        'status' => 'enable',
        'value' => '500'
    ],
]

my php code to add new array to it which is not working :

    $banners = Config('Banners_size');
    $banner = array($request->input('size')=>['status'=>$request->input('status'),'value'=>$request->input('cost')]);

   $bannerinfo = array_merge($banners, $banner);

    Config('Banners_size' , $bannerinfo);
22 Dec
2 years ago

anonymox left a reply on Laravel 5.3 Passport: Password Grant -> Logout

Hi I had your problem, and I solved mine this way :

public function logout(Request $request)
    {
        $value = $request->bearerToken();
        $id= (new Parser())->parse($value)->getHeader('jti');

        $token=  DB::table('oauth_access_tokens')
            ->where('id', '=', $id)
            ->update(['revoked' => true]);

        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        $json = [
            'success' => true,
            'code' => 200,
            'message' => 'You are Logged out.',
        ];
        return response()->json($json, '200');
    }

You should send token in your logour request as Authorization header

19 Dec
2 years ago

anonymox left a reply on Avoiding Laravel From Redirecting User After Login

I've solved this problem by replacing

return redirect('/home');

with proper json response in RedirectIfAuthenticated.php file :

 public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

            $json = [
                'success' => true,
                'code' => 200,
                'message' => 'You are Logged in.',
            ];
            return \Response::json($json,200);
        }

        return $next($request);
    }
18 Dec
2 years ago

anonymox started a new conversation Avoiding Laravel From Redirecting User After Login

I'm trying to show "logged in" message after user logged in to my application, actually when user attempt to login for the first time I will give him/her a jwt token and I want to check if the user is logged in if user attempt to login more than once.

This is the part I have problem :

if($this->attemptLogin($request)){
            return ($this->loginCounter > 0) ? response()->json('Logged in', 200) : ($this->CreateToken($request));
        }

But when attemptLogin is called which will run below code it will redirect user if user is logged in :

 protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

IS there any way to override this ? and return "you are logged in" in response instead of redirecting to a view ?

FYI : I have customized laravel auth scafold , but this part is still making problem for me. I'm using laravel 5.3

15 Dec
2 years ago

anonymox started a new conversation Can't Convert Passport The Refresh Token Is Invalid.,hint:Token Has Expired Exception Error Into Json

I need to convert passport refresh token expired exception error into json but I couldn't figure it out how.

any one know a way to get json response instead of fatal error exception.

FYI : I'm using laravel 5.3

13 Dec
2 years ago

anonymox started a new conversation How To Convert Passport Invalid Refresh Token Exception Into Json Response

I'm using passport for creating tokens and refresh tokens in my project. the problem I'm facing is when I try to login by sending refresh token alongside my login body (which that refresh token is expired) I get invalid request - refresh token expired exception,

and some times I get {"Message":"Failed to log in"} error message when I try to login with expired refresh token.

any idea how to fix this issue?

anonymox started a new conversation How To Stop User Redirection After Receiving Login Request In Laravel 5.3

I have a strange problem, I want to show logged in message after one attempt of user login. I mean if user attempt for the first time he/she gets token, then if he/she send more request exactly like before I want to show a json response to him/her which says your are logged in.

But I couldn't figure it out how. FYI : I'm using my own customized laravel auth scaffold.

AuthenticatesUsers.php :

<?php

namespace App\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use GuzzleHttp\Client;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required', 'password' => 'required',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        isset($request->refresh_token) ? $refreshToken = $request->refresh_token : $refreshToken = null;//Check if login request contain token

        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ? $this->StatusCode($refreshToken,$this->credentials($request),$status=false) : $this->StatusCode($refreshToken,$this->credentials($request),$status=true);
//                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        return \Response::json('Logged In','200');
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        isset($request->refresh_token) ? $refreshToken = $request->refresh_token : $refreshToken = null;//Check if login request contain token

        return $this->StatusCode($refreshToken,$this->credentials($request),$status=false);
//        return redirect()->back()
//            ->withInput($request->only($this->username(), 'remember'))
//            ->withErrors([
//                $this->username() => Lang::get('auth.failed'),
//            ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'email';
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

//        return redirect('/');
        return response()->json('Logged out', '200');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }


    public function StatusCode($refreshToken,$user,$status){

        function GetToken($userobject)
        {
            $http = new Client;

            $response = $http->post('http://localhost/iranAd/public/oauth/token', [ //TODO Make this url dynamic
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => '1',
                    'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
                    'username' => $userobject['email'],
                    'password' => $userobject['password'],
                    'scope' => '',
                ],
            ]);

            return json_decode((string) $response->getBody(), true);
        }

        function RefreshToken($refresh_token)
        {

            $http = new Client;

            $response = $http->post('http://localhost/iranAd/public/oauth/token', [ //TODO Make this url dynamic
                'form_params' => [
                    'grant_type' => 'refresh_token',
                    'refresh_token' => $refresh_token,
                    'client_id' => '1',
                    'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
                ],
            ]);

            return json_decode((string) $response->getBody(), true);//TODO Fix The Token has expired Exception
        }

        if(is_null($refreshToken)){
            return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
        }elseif (isset($refreshToken) && (!empty($refreshToken))){
            return ($status == true) ? response()->json(RefreshToken($refreshToken),200) : response()->json(['Message' => 'Failed to log in'],403);
        }

    }
}

anonymox left a reply on How To Move Laravel Auth Scaffold Into App Directory From Vendor

I've fixed it. with searching for all namespaces and fixing them.

anonymox left a reply on How To Move Laravel Auth Scaffold Into App Directory From Vendor

It has lot's of dependencies and I need to go through them to rewrite it for my self.

I've managed to move it and make login work but when i want to send register request I get :

ReflectionException in Container.php line 749:
Class Illuminate\Auth\Middleware\Authenticate does not exist
12 Dec
2 years ago

anonymox started a new conversation How To Move Laravel Auth Scaffold Into App Directory From Vendor

I'm using laravel 5.3 and I'm trying to move Auth scaffold into app directory instead of vendor, I've moved auth directory from vendor into app. when I want to send login request to my project I get :

ProviderRepository.php line 146:
Class 'Illuminate\Auth\AuthServiceProvider' not found

some body knows how can i properly move it with out any problem and missing part ?

06 Dec
2 years ago

anonymox started a new conversation How To Get Multiple Parameters From Url As Wildcard In Laravel

'm trying to get multiple parameters from url and send them to view but what I get is undefined variable. how to fix this :

api.php

Route::get('adwidth/{width}/adheight/{height}/aduser/{user_id}', function(){
    return view('frame', compact('width','height','user_id'));
});

frame.blade.php

@section('content')
    <h3>{{ $width }}</h3>
@stop

I'm using laravel 5.3

04 Dec
2 years ago

anonymox started a new conversation Redirecting To Home Route After Sending Get Request To Nested Resource Controller

I'm trying to reach to my nested resource controller by passing this url in postman with get method :

    http://peoject.local/api/admin/users/4/seats

my api.php file is like :

      Route::group(['prefix' => 'admin'], function () {
            Route::resource('users', 'Admin\UsersController', ['except' => ['store', 'create', 'edit']]);
    
            Route::resource('users.seats', 'Admin\ASeatController', ['only' => ['index', 'show', 'update', 'destroy']]);
    
            Route::resource('banners', 'Admin\BannersController', ['except' => ['edit', 'create']]);
        });

I want to get the user id in ASeatController :

  /**
         * Display a listing of the resource.
         *
         * @param $userId
         * @return \Illuminate\Http\Response
         */
        public function index($userId)
        {

            try {
                $statusCode = 200;

                $domains = Seat::where('user_id', '=', $userId)->first();
    
            } catch (\Exception $e) {
                $statusCode = 400;
            } finally {
                $response = \Response::json($domains, $statusCode);
                return $response;
            }
        }

But when I test it I redirect to /home, and I don't know why. I followed official laravel docs to do this.

Any Idea how to fix this ?

FYI : I', using laravel 5.3

23 Nov
2 years ago

anonymox left a reply on Laravel Passport Revoke And Prune Event Listener Is Not Doing Anything

I've Solved My problem This way : Step1 - In EventServiceProvider should change the path to the Access Token createdn and also refresh token created :

 protected $listen = [
        'Laravel\Passport\Events\AccessTokenCreated' => [
            'App\Listeners\RevokeOldTokens',
        ],

        'Laravel\Passport\Events\RefreshTokenCreated' => [
            'App\Listeners\PruneOldTokens',
        ],
    ];

Step2- generate this two listeners events :

php artisan event:generate

Step3- Modify AccessTokenCreated & RefreshTokenCreated event handle methods :

namespace App\Listeners;

use Laravel\Passport\Events\AccessTokenCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;

class RevokeOldTokens
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AccessTokenCreated  $event
     * @return void
     */
    public function handle(AccessTokenCreated $event)
    {


        DB::table('oauth_access_tokens')
            ->where('id', '<>', $event->tokenId)
            ->where('user_id', $event->userId)
            ->where('client_id', $event->clientId)
            ->update(['revoked' => true]);


    }
}
<?php

namespace App\Listeners;

use Laravel\Passport\Events\RefreshTokenCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;

class PruneOldTokens
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  RefreshTokenCreated  $event
     * @return void
     */
    public function handle(RefreshTokenCreated $event)
    {

        DB::table('oauth_refresh_tokens')
            ->where('id', '<>', $event->refreshTokenId)
            ->where('access_token_id', '<>', $event->accessTokenId)
            ->update(['revoked' => true]);

    }
}

After This steps if I send any request to my project it will check for tokens and if there is another token it will revoke it and make it unathorized.

anonymox started a new conversation Laravel Passport Revoke And Prune Event Listener Is Not Doing Anything

I've added this two event listeners to my : EventServiceProvider

    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'Laravel\Passport\Events\AccessTokenCreated' => [
            'App\Listeners\RevokeOldTokens',
        ],
    
        'Laravel\Passport\Events\RefreshTokenCreated' => [
            'App\Listeners\PruneOldTokens',
        ],
    ];

And in my AuthServiceProvider I have :

     public function boot()
        {
            $this->registerPolicies();
    
            Passport::routes();
            passport::$revokeOtherTokens;
            passport::$pruneRevokedTokens;
            Passport::tokensExpireIn(Carbon::now()->addDays(1));
            Passport::refreshTokensExpireIn(Carbon::now()->addDays(2));
    
        }

I want passport to revoke all other user access tokens and then prune them if they are revoked. but nothing is happening and every time I request an access token from postman I get a new access Token while there are several access tokens in the database.

15 Nov
2 years ago

anonymox started a new conversation Ssl Connections Are Being Blocked When Trying To Send Post Request To Passport

I'm trying to send post request to laravel5.3 passport via postman but what I get is ssl connections are being blocked. this is 4 days now i'm trying to fix this.

I've added guzzel 6.2 to my composer and also https://curl.haxx.se/ca/cacert.pem into my php.ini but still no success.

please help me out.

I'm using mac os with AMPPS with php5.6.

13 Nov
2 years ago
12 Nov
2 years ago

anonymox left a reply on L5 API For Mobile Devices + Facebook Connect

@visualight @maximl337 did you solve this ? if yes can you say how?

anonymox started a new conversation How To Create Token-Based Authentication(oauth2) For AngularJS And Laravel Apps Via Passport

I created an web app which it uses laravel default registration(auth), I've tested passport oauth2 client access token from taylor tutorial. My web app uses angular js for UI and laravel for backend , so I need to create user, when create user request is sent from angular and then create a global access token to give it in my response to angular which then in all later request I use it to authenticate requests.

actually I want to implement oauth2 authentication for my web app, but so far I've searched a lot but I couldn't find any useful step by step tutorial for it.

anyone can help me out?

FYI: I'm using laravel 5.3 with passport enabled and angular js 1.5 for frontend. Some might say use JWT, what if i want to sign in my user via their social networks ? like facebook or google plus ? does JWT handle that too?

10 Nov
2 years ago

anonymox left a reply on How To Create Oauth Access Token In Register Controller

I've found the solution for creating personal access token in register controller : after creating user in register controller I can put below code to create personal access token in register controller :

 // Creating a token without scopes...
        $token = $user->createToken('Token')->accessToken;

$user in here is the object we've been assigning user information to store in database .

08 Nov
2 years ago

anonymox started a new conversation How To Create Oauth Access Token In Register Controller

I created an web app which it uses laravel default registration, I've tested passport oauth2 client access token from taylor tutorial. My web app uses angular js for UI and laravel for backend , so I need to create user when create user request is sent from angular and then create a global access token to give it in my response to angular which then in all later request I use it to authenticate requests.

How can i do this ?

06 Nov
2 years ago

anonymox started a new conversation How To Get Json File Object And Upload It In Laravel

I want to upload an json file object in laravel , this object come from angular js with the below format:

{
      "key": "lfobj2399fe3b",
      "lfFile": {},
      "lfFileName": "photo-1433354359170-23a4ae7338c6.jpg",
      "lfDataUrl": "blob:http://localhost/14044b8b-9dcb-4461-8e2e-cf5337611396",
      "element": {
        "0": {
          "ng339": 198
        },
        "length": 1
      }
    } 

This is the plugin i've used to implement file upload in angular js : https://github.com/shuyu/angular-material-fileinput

I've tried :

if ($request->hasFile('banners')) {
                return \Response::json('file available',$statusCode);
            }

to check if any file is available in my input but i got nothing. if i want to get this object as an object i get it's value by using :

            $banners = $request->input('banners');

but i can't upload any file with this input. how can i get this object and upload it in laravel ?

03 Nov
2 years ago

anonymox left a reply on How To Check Is Checkbox Is Selected And Post It's Data Using Jquery In Laravel

You don't need to check for unchecked status in your jquery code , and also you can submit your form instead of using post method :

    <script>
        $(document).ready(function () {

            var activate = "<?php echo $activate; ?>";
            if(activate == 'true'){
                $("#webTargeting").prop('checked', true);
            }else{
                $("#webTargeting").prop('checked', false);
            }

            $('#webTargeting').change(function() {
                $('#webTargeting').val($(this).is(':checked'));
                $("#webTargeting").prop('value', true);
                $(this).closest('form').submit();
            });

        });
    </script>
30 Oct
2 years ago

anonymox left a reply on Eloquent Is Injecting Statement To Query By Default

So how can i use it for this matter ? (Sorry I'm new to laravel)

anonymox left a reply on Eloquent Is Injecting Statement To Query By Default

I've managed to solve my problem using with() method thanks to @habeebnet and @Snapey : I wanted to check if logged in user has specified role - then he/she can access the specified route to do so i had checkRole middleware that it will search for the user role in database and if it matches the roles specified to the route he/she could access that.

web.php : How i specified my roles to each view or controller

Route::get('/home', '[email protected]')->middleware('roles:ADMIN|MANAGER|ADVERTISER|PUBLISHER|AGENCY');

CheckRole middleware :

class CheckRole
{

    public function handle($request, Closure $next, $role)
    {

        $roles = explode('|',$role);
        
        if ($request->user() === null){
            return response(trans('objects.401'), 401);
        } else if ($request->user()->hasAnyRole($roles) || !$roles){
            return $next($request);
        }
        return response(trans('objects.401'), 401);
        
    }
}

User Model :

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'fullname', 'password', 
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
    }

    public function hasAnyRole($roles)
    {
        $user = Auth::User();
        $userId = $user->id;

        if (is_array($roles)) {
            foreach ($roles as $role) {

                if ($this->hasRole($role,$userId)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles,$userId)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role,$userId)
    {
        if ($this->roles()->with('users')->where('user_id' ,'=' , $userId , 'and')->where('name', '=' , $role)->first()){
            return true;
        }
        return false;
    }

}

The important part is :

$this->roles()->with('users')->where('user_id' ,'=' , $userId , 'and')->where('name', '=' , $role)->first()

anonymox left a reply on Eloquent Is Injecting Statement To Query By Default

actually i want to get the all users roles - something like :

select * from users 
inner join  user_role on (users.id = user_role.user.id)
inner join roles on (user_role.role_id = roles.id)

But what i'm doing with eloquent is obviously wrong.

in fact i want to check in my checkRole middleware this :

public function handle($request, Closure $next, $role)
    {

        $roles = explode('|',$role);

        if ($request->user() === null){
            return response(trans('objects.401'), 401);
        } else if ($request->user()->hasAnyRole($roles) || !$roles){
            return $next($request);
        }
        return response(trans('objects.401'), 401);


        if (!$request->user()->hasRole($roles)) {
            return response(trans('objects.401'), 401);
        }
        return $next($request);

    }
}

And My hasRole and hasAnyRole Methods are :

 public function hasAnyRole($roles)
    {
       
        if (is_array($roles)) {
            foreach ($roles as $role) {

                if ($this->hasRole($role)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles,)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role)
    {
        if ($this->roles()->where('name' , $role)->first()){
            return true;
        }

        return false;
    }

anonymox started a new conversation Eloquent Is Injecting Statement To Query By Default

I have users table and roles and also user_role tables - which my User Model contain :

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Auth;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'role', 'sex', 'fullname', 'mobile', 'mobile_prefix', 'email', 'co_name', 'tel', 'tel_prefix',
        'password', 'balance', 'last_login_time', 'last_ip',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
    }

    public function hasAnyRole($roles)
    {
        $user = Auth::User();
        $userId = $user->id;

        if (is_array($roles)) {
            foreach ($roles as $role) {
                dd($this->hasRole('MANAGER'));

                if ($this->hasRole($role)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles,$userId)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role,$userId)
    {
        if ($this->roles()->where('user_id' ,'=' , $userId , 'and')->where('name', '=' , $role)->first()){
            return true;
        }
        return false;
    }
}

My Role model is :

namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
    public function users(){
        return $this->belongsToMany('App\User', 'user_role' , 'role_id', 'user_id'); //fixed
    }
}

And this is my userTableSeeder :

use Illuminate\Database\Seeder;
use App\Role;
use App\User;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $role_admin = Role::where('name', 'ADMIN')->first();
        $role_manager = Role::where('name', 'MANAGER')->first();
        $role_advertiser = Role::where('name', 'ADVERTISER')->first();
        $role_publisher = Role::where('name', 'PUBLISHER')->first();
        $role_agency = Role::where('name', 'AGENCY')->first();

        $admin = new User();
        $admin->role = 'ADMIN';
        $admin->sex = 'M';
        $admin->fullname = 'fox brain';
        $admin->mobile = '9135694586';
        $admin->mobile_prefix = '98';
        $admin->email = '[email protected]';
        $admin->co_name = 'test';
        $admin->tel = '123456';
        $admin->tel_prefix = '51';
        $admin->password = bcrypt('ali');
        $admin->balance = '1200';
        $admin->last_ip = '127.0.0.1';
        $admin->save();
        $admin->roles()->attach($role_admin);

        $manager = new User();
        $manager->role = 'MANAGER';
        $manager->sex = 'M';
        $manager->fullname = 'alex parker';
        $manager->mobile = '9135694586';
        $manager->mobile_prefix = '98';
        $manager->email = '[email protected]';
        $manager->co_name = 'test';
        $manager->tel = '123456';
        $manager->tel_prefix = '51';
        $manager->password = bcrypt('alex');
        $manager->balance = '1200';
        $manager->last_ip = '127.0.0.1';
        $manager->save();
        $manager->roles()->attach($role_manager);
    }
}

My problem is when I test my code in artisan tinker with :

$role = new Role();
$role->users()->get();

What I get when I check this query is :

string(212) "select `users`.*, `user_role`.`role_id` as `pivot_role_id`, `user_role`.`user_id` as `pivot_user_id` from `users` inner join `user_role` on `users`.`id` = `user_role`.`user_id` where `user_role`.`role_id` is null"

The part which is auto injecting to my query is :

where `user_role`.`role_id` is null

Which make my code not to work and return null ! Any Idea how to solve this problem ?

24 Oct
2 years ago

anonymox left a reply on How To Get Client Ip Address In Register Controller In Laravel 5.3 With Passport Enabled

I've managed to solve this problem using : \Request::ip()

protected function create(array $data) { return User::create([ 'role' => $data['role'], 'sex' => $data['gender'], 'fullname' => $data['fullname'], 'mobile' => $data['mobile'], 'mobile_prefix' => $data['mobile_prefix'], 'email' => $data['email'], 'co_name' => $data['co_name'], 'tel' => $data['tel'], 'tel_prefix' => $data['tel_prefix'], 'password' => bcrypt($data['password']), 'balance' => $data['balance'], 'last_ip' => \Request::ip(), ]);

}
23 Oct
2 years ago

anonymox started a new conversation How To Get Client Ip Address In Register Controller

Hi i want to get the client ip address in my laravel project when registering, I've found some solutions that says get the ip using request global function like :

Protected function create(array $data, Request $request){ Return user::create([ 'name' => $data['name'], 'ip' => $request->ip(); ]); }

But because I'm using passport in my project and it added guzzel to the project when i add : Use Illuminate\Http\Request; To my project it gives me error message of conflicting with guzzel Request.

How can i solve this?

anonymox started a new conversation How To Add Multilingual Support To Laravel 5.3 ?

How To Add Multilingual Support to laravel 5.3 ? I've found this thread but it's no longer useful for laravel 5.3 : https://laracasts.com/discuss/channels/tips/example-on-how-to-use-multiple-locales-in-your-laravel-5-website