AdRock

AdRock

Member Since 2 Years Ago

Experience Points 880
Experience Level 1

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 Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

12 Jun
6 days ago

AdRock 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

AdRock left a reply on 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

11 Jun
1 week ago

AdRock 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.

06 Jun
1 week ago

AdRock left a reply on 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

05 Jun
1 week ago

AdRock 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');
    // }
}
```
03 Jun
2 weeks ago

AdRock 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

25 May
3 weeks ago

AdRock left a reply on Download File From Storage Doesn't Work When Using Parameter For Filename

One last question, how do i delete the file after downloading?

I get the following error

The Response content must be a string or object implementing __toString(), "boolean" given.

// force download the file
        $response = response()->download($pathToFile, $download, $headers);

        // and remove it from storage as no longer needed
        return Storage::disk('public')->delete($pathToFile);

AdRock 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

22 May
3 weeks ago

AdRock left a reply on 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');

AdRock left a reply on 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

AdRock left a reply on Add Custom Attribute To Auth:user() During Login

@SNAPEY - This is how the data was stored in the database.

AdRock 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?

AdRock left a reply on 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.

21 May
4 weeks ago

AdRock left a reply on Auth::user() Returns Null Using Custom Login

Yeah, I can dump out the user in the LoginController

AdRock left a reply on Auth::user() Returns Null Using Custom Login

I've updated my LoginController to show my $user

AdRock left a reply on Auth::user() Returns Null Using Custom Login

just tried a var_dump() and still get the same

AdRock left a reply on Auth::user() Returns Null Using Custom Login

Everythine including $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

AdRock 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


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)
     {
        $user = ...
        
         // 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?

AdRock left a reply on 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

20 May
4 weeks ago

AdRock 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

13 May
1 month ago

AdRock left a reply on @push And @stack Don't Seem To Load Javascript

I fixed the problem. It had to do with the defer attribute in the script tag

<script src="{{ asset('js/app.js') }}" defer></script>

Once removed all my plugins started to work

AdRock left a reply on @push And @stack Don't Seem To Load Javascript

@ANDREICH1980 - Yes

$(document).ready(function () {
            $('.SlectBox').SumoSelect();
     });

What is weird is the other plugins are loading and work perfectly. It's just Sumoselect that is causing a problem so jQuery is loading and everything else is loading.

AdRock started a new conversation @push And @stack Don't Seem To Load Javascript

I have come back to using Laravel after a long break and am now using 5.8

I have created my template and included views etc but I've got a problem loading jQuery plugins.

I've tested to make sure jQuery is loaded and it is but any plugins I load using @push don't appear to load although I can see them in the source and console.

They must be loading as the reports.js file is kicking up a stink about

Uncaught TypeError: $(...).SumoSelect is not a function

When I run a test to see if any of the plugins are loaded, the console says none of them are.

This is my main template

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <!-- push target to head -->
    @stack('styles')
</head>
<body>
    <div id="app">
        
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <!-- or push target to footer -->
    @stack('scripts')
</body>
</html>

This is my view which causes the problem

@extends('layouts.main')

@section('content')
...
...
...
@endsection

@push('styles')
<link href="{{ asset('libraries/sumoselect/css/sumoselect.css') }}" rel="stylesheet" media="screen">
<link href="{{ asset('libraries/flatpickr/css/flatpickr.min.css') }}" rel="stylesheet" media="screen">
@endpush

@push('scripts')
<script src="{{ asset('libraries/sumoselect/js/jquery.sumoselect.min.js') }}"></script>
<script src="{{ asset('libraries/chartjs/js/Chart.min.js') }}"></script>
<script src="{{ asset('libraries/flatpickr/js/flatpickr.js') }}"></script>

<script src="{{ asset('js/reports/reports.js') }}"></script>
@endpush

and finally this is my reports.js

$('#report-types, #base-chart-types').SumoSelect({ 
        okCancelInMulti: true ,
        triggerChangeCombined: false,
        isClickAwayOk: true,
        selectAll: true,
        forceCustomRendering: true
    });
22 Feb
2 years ago

AdRock left a reply on Can't Login Using Entrust

I got it working.

The User model code was incorrect and wasn't documented as far as i could see

i changed my code to this and it worked

namespace App;

use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;


class User extends \Illuminate\Foundation\Auth\User
{
16 Feb
2 years ago

AdRock started a new conversation Can't Login Using Entrust

I've been trying to get Entrust working with Laravel 5 following the instruction here https://github.com/Zizaco/entrust

I've made all the changes as requested, added users and roles (I haven't added permissions as I won't need to check them...just roles), assigned roles to user and when I try to log in a user I get this error message

Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\User given, called in C:\www\procurement2\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php on line 385 and defined

I've no idea what this error means or how to fix it

Here is all the code changes App/User.php


namespace App;

use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent
{
    use EntrustUserTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'lastname', 'email', 'password', 'userlevel', 'buyer'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}```
App/Http/Kernel.php
 ```protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
        'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
        'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,
    ];```
App/config/app.php
```'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        ...

        /*
         * Package Service Providers...
         */
        Zizaco\Entrust\EntrustServiceProvider::class,
];

'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        ...

        'Entrust'   => Zizaco\Entrust\EntrustFacade::class,

    ],```
App/config/auth.php
```'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
            'table' => 'users',
        ],```
09 Feb
2 years ago

AdRock started a new conversation Problems With Entrust

I am trying to use Entrust to add roles to my users but I've hit a brick wall.

I've been following the instructions on GitHub https://github.com/Zizaco/entrust#usage and I've got up the the usage section.

I need to add some users but I get the following error

FatalErrorException in EloquentUserProvider.php line 130: Class '\App\User' not found

I updated my User.php to this (in default location)

<?php

use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent
{
    use EntrustUserTrait; // add this trait to your user model

    ...
}

Also after this problem is fixed and I have users in database, how do i run the following code to create roles etc. Would i create a controller and run it?

$owner = new Role();
$owner->name         = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description  = 'User is the owner of a given project'; // optional
$owner->save();
30 Jan
2 years ago

AdRock started a new conversation Custom Validation Method [validateUniqueWith] Does Not Exist.

I am having problems with custom validation. Whenever i try to validate using a custom validation rule I get this error

BadMethodCallException in Validator.php line 3396: Method [validateUniqueWith] does not exist.

I've been following a similar question on here where I found the example code. I've tailored it as I use Laravel 5.3 as there is no Services folder I have created a service provider

ValidationServiceProvider.php
<?php 

namespace App\Providers\Validation;

use Validator;
use Illuminate\Support\ServiceProvider;
use App\Providers\Validation\UniqueWithValidator;

class ValidationServiceProvider extends ServiceProvider {


    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        #
    }

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        $this->uniqueWithValidator();
    }

    private function uniqueWithValidator()
    {
        // Need to override the default validator with our own validator
        // We can do that by using the resolver function
        Validator::resolver(function ($translator, $data, $rules, $messages)
        {
            // This class will hold all our custom validations
            return new UniqueWithValidator($translator, $data, $rules, $messages);
        });
    }
}

I have created a directory called Validation in the Providers directory and I've placed this file inside it

<?php 

namespace App\Providers\Validation;

use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;

class UniqueWithValidator extends Validator {

    public function validateUniqueWith($attribute, $value, $parameters)
    {
        $result = DB::table($parameters[0])->where(function($query) use ($attribute, $value, $parameters) {
            $query->where($attribute, '=', $value) // where firstname = value
                ->orWhere($parameters[1], '=', $value); // where lastname = value
        })->first();

        return $result ? false : true;
    }
}

I'm convinced it's to do with namespacing but not sure.

19 Jan
2 years ago

AdRock left a reply on Custom Validation Required In Other Field In Whitelist Array

I solved it by using

$rules = [
    'colour' => 'required_unless: otherfield,' . implode(',', $whitelist),
];

AdRock left a reply on Custom Validation Required In Other Field In Whitelist Array

I think combination of required_if and not_in is what i'm trying to do

AdRock left a reply on Custom Validation Required In Other Field In Whitelist Array

I know how to do that as I use that already in other rules but I only want to apply that rule to a required so that it's required if that value is in the array.

Any idea how to do that?

AdRock started a new conversation Custom Validation Required In Other Field In Whitelist Array

I am really struggling getting some custom validation to work and need help!!

I am looking for a rule similar to required_if but instead of looking for a value which equals something, I want to have a value which is in an whitelist array.

    'red',
    'yellow',
    'green',
    'blue',
    'black'```
);

here is the rule I've created

```$rules = array(
    'colour' => 'colour_required:' . $product['colour'] . ',' .implode(',', $whitelist),
);```


and in App\Providers\AppServiceProvider.php I've added a custom validation function

```Validator::extend('colour_required', function ($attribute, $value, $parameters, $validator) {
    $colour = $parameters[0];
    $whitelist = explode(',', $parameters[1]); 
    
    return !in_array($colour, $whitelist);
}, 'ffghgjghjg');```

it never works. I always get an validation message saying the colour is required even if it's in the whitelist