AdRock

AdRock

Member Since 2 Years Ago

Experience Points
880
Total
Experience

4,120 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
0
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.

Level 1
880 XP
Jun
12
5 months ago
Activity icon

Started a new Conversation Replace Collection Key Value With Null

I have a collection retrieved by Eloquent and I want to replace all occurrences of a specific key with a value of null

I have tried using the reject()

$collection = $collection->reject(function ($value, $key) {
     return $key == 'model';
});

and also transform but get the same result

$collection->transform(function($item) {
    $item->mondel = null;
    return $item;
});

For both I don't get null but and empty string

Activity icon

Replied to How To Check If Relationship Exists In Elqouent Collection

@TYKUS - Thanks @tykus

$test = $collection->filter->relationLoaded('make')->isEmpty();

This was exactly what I was looking for

Jun
11
5 months ago
Activity icon

Started a new Conversation How To Check If Relationship Exists In Elqouent Collection

I am building an Eloquent collection based on what the user has selected on a form. If they check specific checkboxes on the form, I dynamically create a relation. This works perfectly.

$collection = MyModel::when(!is_null($request->input('make')), function($query) {
    $query->with('make');
 })

When I do dd($collection) I see the relations

How can I check for the existence of the relation? I have tried dd($collection->contains('make')); but it return false.

EDIT

I have tried this but it returns true even if it doesn't exist in the collection

$test = $collection->contains(function ($value, $key) {
    return $value['make'];
});
Jun
06
5 months ago
Activity icon

Replied to Cannot Auth::logout() Using Multi Tenancy, SQL Error

I just uncommented my logout function and removed Auth::logout()

Now it redirects to login as expected and doesn't let me access restricted pages

Jun
05
5 months ago
Activity icon

Started a new Conversation Cannot Auth::logout() Using Multi Tenancy, SQL Error

I created my own multi tenant login and authentication which works fine with no problems.

The only problem I have is when I want to log the use out. When i click the logout link I get this error

SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO) (SQL: select * from people where id = 109304 limit 1)

I don't know where the logout function is so added it to my controller but I still get the same problem.

Do I need to update somewhere else or do something different in my logout function?

Here is my login controller

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
...
...
...

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
     public function __construct()
     {
         $this->middleware('guest')->except('logout');
     }

     public function login(Request $request)
     {
         // Check validation
         $this->validate($request, [
             'username' => 'required|regex:/^([a-z0-9-_\.]+)*@([a-z0-9-]+)$/',
             'password' => 'required'
         ]);

         list($username, $database) = explode("@", $request->input('username'));

         // Get user record
         $organisation = Organisation::where('dbName', $database)
            ->first();

        if(!$organisation) {
            return redirect()->back()->withErrors(['error' => ['Access denied: Incorrect login details']]);
        }

        // No way of setting an extra parameter against the user. Could be because of inheritance
        $request->session()->put('orgId', $organisation->id);

        $company = new Company();

        $company->hostname = '55.55.55.55'; //$organisation->dbHostname;
        $company->username = Crypt::decryptString($organisation->dbUser2);
        $company->password = Crypt::decryptString($organisation->dbPassword2);
        $company->database = $organisation->dbName;

        // connect to client database
        $company->connect();

        $user = User::where('username', $username)
            ->where('portalAccess', 1)
            ->where('isActive', 1)
            ->first();

        if (!Hash::check($request->input('password'), $user->password2)) {
            ...
            ...
            ...
        }

        // Set Auth Details
        \Auth::login($user);

        // Redirect home page
        return redirect()->route('dashboard.index');
    }
    //
    // /**
    //  * Log the user out of the application.
    //  *
    //  * @param  \Illuminate\Http\Request  $request
    //  * @return \Illuminate\Http\Response
    //  */
    // public function logout(Request $request)
    // {
    //     \Auth::logout();
    //     $request->session()->flush();
    //     $request->session()->regenerate();
    //
    //     return redirect()->route('login');
    // }
}
```
Jun
03
5 months ago
Activity icon

Started a new Conversation Get Values From Relation In Collection After Get()

I call a model with a relationship like this

$tickets = Ticket::with('type')->get();

How can I get the distinct rows from the relation?

Each $ticket will have a relation called type in there are fields for id and type.

I could do another DB query to get this information but if I can get it from the collection I'd rather do that

May
25
5 months ago
Activity icon

Started a new Conversation Download File From Storage Doesn't Work When Using Parameter For Filename

I am trying to download a file from storage which downloads ONLY when I hardcode values for the file. This isn't what I want as I can make a reusable function where i can pass parameters for a filename.

This works as expected when I hardcode filename;

$date = (new DateTime())->format('d-m-Y H:i:s');

        $headers = array(
            'Content-Type:' => 'application/pdf',
            'Content-Disposition' => 'attachment;filename="' . $download. '_' . $date . '.pdf"',
            'Content-Length: ' =>  Storage::disk('public')->size('5ce95e577efec.pdf'),
            'Pragma' => ' no-cache',
            'Expires' => ' 0'
        );

        return Storage::disk('public')->download('5ce95e577efec.pdf', $download . '_' . $date . '.pdf', $headers);

but when I do this, it does nothing.

// get the filename from ajkax
        $filename = $request->input('filename');
        // get today's date
        $date = (new DateTime())->format('d-m-Y H:i:s');
        // create a new user friendly filebnamne for download
        $download =  $request->input('title') . '_' . $date . '.pdf';

        $headers = array(
            'Content-Type:' => 'application/pdf',
            'Content-Disposition' => 'attachment;filename="' . $download . '"',
            'Content-Length: ' =>  Storage::disk('public')->size($filename),
            'Pragma' => ' no-cache',
            'Expires' => ' 0'
        );

        // force download the file
        Storage::disk('public')->download($filename, $download, $headers);

I'm baffled why using a parameter got a filename would stop it working

May
22
5 months ago
Activity icon

Replied to Add Custom Attribute To Auth:user() During Login

I've tried what you suggested but i still don't see the attribute when I dump out the user.

I've updated my model ...

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    public $orgId;

    // protected $appends = ['orgId'];

    protected $connection = 'tenant';

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'people';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['orgId'];

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

... and added the other bit to the controller

...
...
$user->orgId = 1234;
      
/ / Set Auth Details
\Auth::login($user);

// Redirect home page
return redirect()->route('dashboard');
Activity icon

Replied to Add Custom Attribute To Auth:user() During Login

Basically, the user logs in and the LoginController get the user and before assigning the user to Auth, I need to add some extra properties to the user that aren't stored in any database.

For example I would like to add an orgId property so I can do something like Auth::user()->orgId

Activity icon

Replied to Add Custom Attribute To Auth:user() During Login

@SNAPEY - This is how the data was stored in the database originally. Not down to me and I can't do anything about that

As for the organisation->id, I've just removed the code that gets that

Activity icon

Started a new Conversation Add Custom Attribute To Auth:user() During Login

I know this has been asked before but it doesn't help in my situation.

I have a similar problem to this https://laracasts.com/discuss/channels/laravel/add-a-new-attribute-in-authuser-session-in-laravel-53

I need to add some attributes to my User object when the user logs in.

I've tried using $user->setAttribute() but it doesn't work

Here is my LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use \DB;
// Models
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
     public function __construct()
     {
         $this->middleware('guest')->except('logout');
     }

     public function login(Request $request)
     {
         // Check validation
         $this->validate($request, [
             'username' => 'required',
             'password' => 'required'
         ]);

         $xyz = \Config::get('constants.salt1');

         $user = User::whereRaw('password = AES_ENCRYPT("' . $request->input('password') . '", "' . $xyz . '")')
            ->where('username', $username)
            ->where('isActive', 1)
            ->first();

        
        $user->setAttribute('orgId', $organisation->id);
        // $user->orgId = $organisation->id;
        
        // Set Auth Details
        \Auth::login($user);

        // Redirect home page
        return redirect()->route('reports.index');
    }
}

and my User model

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $appends = ['orgId'];

    protected $connection = 'tenant';

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'people';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [''];

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

    public function getOrgIdAttribute($value)
    {
        return $value;
    }
}

Any idea how do i get this working. It seems pointless creating a session like in the post i referenced and the values aren't coming from another model?

Activity icon

Replied to Auth::user() Returns Null Using Custom Login

@sirhxalotot, thanks for your help. It was getting late and I had time to think last night and this morning and I've now got it working.

I think it was to do with the User model but after stripping my code back and putting it back in bit at a time, enabled me to find where it was going wrong.

May
21
5 months ago
Activity icon

Replied to Auth::user() Returns Null Using Custom Login

Yeah, I can dump out the user in the LoginController

Activity icon

Replied to Auth::user() Returns Null Using Custom Login

I've updated my LoginController to show my $user

Activity icon

Replied to Auth::user() Returns Null Using Custom Login

just tried a var_dump() and still get the same

Activity icon

Replied to Auth::user() Returns Null Using Custom Login

Everythine between $user and \Auth::login($user); is where I get my user and it returns a User object.

I do the \Auth::login($user); and when I do dd(\Auth::user()->portalPermissions); I see the permissions for the user. However when i try to get the user in another controller it returns null so it's like it's not storing the user in a session or however the auth does it

Activity icon

Replied to Auth::user() Returns Null Using Custom Login

I was following this article

https://laravelcode.com/post/laravel-55-login-with-only-mobile-number-using-laravel-custom-auth

I'm not using a custom service provider, just overriding the login function as it the article.

The $user in my controller login function is an object after I've got the user from the database

Activity icon

Started a new Conversation Auth::user() Returns Null Using Custom Login

I am having a problem getting a logged in user's details in other controllers. If i do dd(Auth::user()) in any controller it returns null

Here is my LoginController

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
     public function __construct()
     {
         $this->middleware('guest')->except('logout');
     }

     public function login(Request $request)
     {
        $xys = '1234'
        $user = \User::whereRaw('password = AES_ENCRYPT("' . $request->input('password') . '", "' . $xyz . '")')
            ->where('username', $username)
            ->where('portalAccess', 1)
            ->where('isActive', 1)
            ->first();
        
         // Set Auth Details
         \Auth::login($user);

         dd(\Auth::user()->portalPermissions);

         // Redirect home page
         return redirect()->route('home');
     }
}

And my routes

Route::group(['prefix' => 'reports', 'as' => 'reports', 'middleware' => ['company']], function() {
    Route::get('/', ['as' => 'index', 'uses' => '[email protected]']);

I can get the authed user in my LoginContoller no problem and I can see their permissions but not in any other controllers. Do I need to do something different in my routes. It's been a while since I last did this?

Activity icon

Replied to Custom Login And Authentication

Thanks grenadecx

I knew there was a way but not having used Laravel for over 6 months and not having done this before, it was a headache.

My tenant stuff needs to go in the login function you shown so I get the client database from their domain name and then get the user from the client database.

Everything is working fine now and is much easier than i thought

May
20
5 months ago
Activity icon

Started a new Conversation Custom Login And Authentication

I don't know if this has ever been asked before but I'll ask anyway as searches don't return what I'm looking for/

I need a custom login/authentication for Laravel 5.8

The login for would look exactly the same.

When the user enters their email and password, I need the login/auth to get the domain of the email which is a database I connect to. and then connect to that database to search for the username which is the first part of the email.

I am already using tenants to get data from different database depending on what connection I tell it to use. I am not sure how to update which files to do the authentication.

This is how I see it working

  1. User enters email and password and submits
  2. The login/auth explodes the email address and the domain is the connection to use
  3. Query the main database and get the connection details (I can do this already, just need to be part of auth)
  4. Query the customer database to get the username and password that match what the user logged in with

I can do most of it, I just don't know how to update the Auth