I created a new class under /app/UserRepositories/UserRepository.php.
Now i want to use it in my AuthenticateUser.php under /app.
I tried to import it like that use App\Repositories\UserRepository;
but I get still the same error: Class does not exist
UserRepository.php
<?php use App\Repositories;
use App\User;
class UserRepository {
public function updateOrCreate($userData)
{
return User::firstOrCreate([
'username' => $userData->username,
'email' => $userData->email,
'avatar' => $userData->avatar
]);
}
}
At the beginning of your file /app/UserRepositories/UserRepository.php, you will need to namespace it using:
namespace App\UserRepositories;
Then you can import it to be used anywhere by:
use App\UserRepositories\UserRepository;
Related
I am using laravel 6. I have a service provider class called DriveServiceProvider. This class has all the dependencies that are needed to connect with google drive.The following is my Service Provider
<?php
use Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter;
use League\Flysystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Storage;
class DriveServiceProvider extends ServiceProvider
{
public function register(){
}
public function boot()
{
Storage::extend('google',function( $app,$config){
$client=new \Google_Client();
$client->setClientId($config['clientId']);
$client->setClientSecret($config['clientSecret']);
$client->refreshToken($config['refreshToken']);
$service=new \Google_Service_Drive($client);
$adapter=new GoogleDriveAdapter($service,$config['folderId']);
return new FileSystem($adapter);
});
}
}
I want to pass this service provider to a controller, the following is my controller
<?php
namespace App\Http\Controllers\Cloud;
use App\Http\Controllers\Controller;
use App\Providers\DriveServiceProvider;
use Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter;
use Illuminate\Support\Facades\Cache;
use League\Flysystem\Filesystem;
class uploadFileController extends Controller{
public $filesystem;
//Attempting Dependency Injection
public function __construct(DriveServiceProvider $filesystem) {
$this->filesystem=$filesystem;
}
public function createFolder(){
$directoryName='Demo';
$this->filesystem->createDir($directoryName);
//return $$filesystem->folder_id;
}
public function deleteFolder($id){
$this->filesystem->delete();
}
}
When i run the script , it's throwing the fllowing error
Illuminate\Contracts\Container\BindingResolutionException
Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class
Illuminate\Support\ServiceProvider
What's wrong with my code ? any help is appreciated.
There is an easier approach to do Google Drive implementation in Laravel install.
composer require nao-pon/flysystem-google-drive
In filesystems.php include your google config.
'google' => [
'driver' => 'google',
'clientId' => env('GOOGLE_DRIVE_CLIENT_ID'),
'clientSecret' => env('GOOGLE_DRIVE_CLIENT_SECRET'),
'refreshToken' => env('GOOGLE_DRIVE_REFRESH_TOKEN'),
'folderId' => env('GOOGLE_DRIVE_FOLDER_ID'),
],
Now you should be able to get your files like so.
Storage::disk('google')->get('yourfile');
This is inspired by this following tutorial.
Currently working on an Excel import functionality. I want to import the Excel sheet and display its information on another page using a foreach loop. However it seems to be rather hard for some reason. When I die and dump the collection data (used this because import would error) it shows everything correctly. The data in the spreadsheet is where it should be. So I feel that is fine. However I cannot get it inserted into my database for some odd reason. I have a header row so I use the WithHeaderRow functionality.
DataImport class:
<?php
namespace App\Imports;
use App\Data;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');
class DataImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Data([
'cliëntnummer' => $row['clientnummer'],
'zoeknaam' => $row['zoeknaam'],
'naam' => $row['naam'],
'omschrijving' => $row['omschrijving'],
'plaats' => $row['plaats'],
'week' => $row['week'],
'vennoot' => $row['vennoot'],
'relatiebeheerder' => $row['relatiebeheerder'],
'samensteller' => $row['samensteller'],
'ADVer' => $row['adver'],
'cliëntgroepcode' => $row['clientgroepcode'],
'accountant' => $row['accountant'],
'samenstellen' => $row['samenstellen'],
'ADV jaarwerk' => $row['ADVJaarwerk'],
'periodieke ADV' => $row['periodiekeADV'],
'fiscaliteiten' => $row['fiscaliteiten'],
]);
}
}
Datacontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\DataImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class DataController extends Controller
{
public function index(){
return view('importeren');
}
public function import(Request $request){
$datas = Excel::toCollection(new DataImport(), $request->file('import_file'));
dd($datas);
return redirect()->route('/home');
}
}
Data Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Data extends Model
{
protected $fillable = [
'id', 'cliëntnummer', 'zoeknaam', 'naam', 'omschrijving', 'plaats', 'week', 'vennoot', 'relatiebeheerder', 'samensteller', 'ADVer', 'cliëntgroepcode', 'accountant', 'samenstellen', 'ADV jaarwerk', 'periodieke ADV', 'fiscaliteiten',
];
}
Spreadsheet data:
Database table layout:
Datadump results:
If I left anything out feel free to tell me. I hope this is sufficient.
Turns out I forgot to reference my datamodel in the file, after finalizing the code of my controller like below it now works (almost) seamlessly.
<?php
namespace App\Imports;
use App\Data;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');
class DataImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Data([
'cliëntnummer' => $row['Cliëntnummer'],
'zoeknaam' => $row['Zoeknaam'],
'naam' => $row['Naam'],
'omschrijving' => $row['Omschrijving'],
'plaats' => $row['Plaats'],
'week' => $row['Week'],
'vennoot' => $row['Vennoot'],
'relatiebeheerder' => $row['Relatiebeheerder'],
'samensteller' => $row['Samensteller'],
'ADVer' => $row['ADVer'],
'cliëntgroepcode' => $row['Cliëntgroepcode'],
'accountant' => $row['Accountant'],
'samenstellen' => $row['Samenstellen'],
'ADVJaarwerk' => $row['ADVJaarwerk'],
'PeriodiekeADV' => $row['PeriodiekeADV'],
'fiscaliteiten' => $row['Fiscaliteiten'],
]);
}
}
is there a way to disable mass assignment protection for all models across all tests without having to duplicate this over and over?
FooTest
Foo::unguard();
Bar::unguard();
Baz::unguard();
Foo::create(['column' => 'value']);
Bar::create(['column' => 'value']);
Baz::create(['column' => 'value']);
BarTest
Foo::unguard();
Bar::unguard();
Baz::unguard();
Foo::create(['column' => 'value']);
Bar::create(['column' => 'value']);
Baz::create(['column' => 'value']);
BazTest
Foo::unguard();
Bar::unguard();
Baz::unguard();
Foo::create(['column' => 'value']);
Bar::create(['column' => 'value']);
Baz::create(['column' => 'value']);
I figured it out using the TestCase every Test class extends, and the Eloquen\Model every model extends.
tests/TestCase.php
<?php
namespace Tests;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
Model::unguard();
}
}
I have created a custom authentication and everything is working fine.
Now I am trying to add the Throttlelogins to prevent multiple incorrect login attempts. But The ThrottleLogins doesn't seem to load.
Q: What am I missing here? or am I doing something wrong?
The exception:
Method
App\Http\Controllers\Auth\CustomersLoginController::hasTooManyLoginAttempts
does not exist.
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Auth;
class CustomersLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:customers');
}
public function ShowLoginForm()
{
return view('auth.customer-login');
}
public function login(Request $request)
{
$v = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if(Auth::guard('customers')->attempt(['email'=>$request->email,'password'=>$request->password],$request->remember)){
return redirect()->intended(route('customerdashboard'));
};
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
public function username()
{
return 'email';
}
}
Error Message
Can someone please explain what am I mssing?
The error says you are missing a function: hasTooManyLoginAttempts
In the function login you can see it's trying to call the function but it does not exist in your class. This is where it goes wrong.
update
In the AuthenticateUsers class, which you tried to copy, it's using ThrottlesLogins trait, which you are missing in your controller.
Update your controller like so:
class CustomersLoginController extends Controller
{
use ThrottlesLogins;
Another update
You tried to import the Trait which Laravel uses in their own Login. However this will not work here's why:
When you define a class, it can only have access to other classes within its namespaces. Your controller for instance is defined within the following namespace.
namespace App\Http\Controllers\Auth;
So to use other classes, you need to import them from their own namespaces so you can access them. e.g.:
use Illuminate\Foundation\Auth\ThrottlesLogins;
Now that you have imported the ThrottlesLogins, which is actually a trait, now inside the class you use it to expose all of the methods inside.
I have tried so much to get this database seed to work but I still get Class 'Account' not found even though I have namespaced where I should.
There error is thrown when running php artisan db:seed on $accountOut = Account::create(array( where Account is what is throwing the error. Am stating the using incorrectly? If I were to remove all the namespacing I have no issues at all.
My Account.php file:
<?php namespace App\Models;
class Account extends \Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'account';
/**public function user()
{
return $this-belongsTo('User');
}*/
}
My seed file:
<?php
use App\Models;
class TransactionSeeder extends Seeder {
public function run()
{
DB::table('transaction')->delete();
DB::table('account')->delete();
$accountOut = Account::create(array(
'name' => 'Checking',
'origin' => 'Bank'
));
$accountIn = Account::create(array(
'name' => 'Stuff',
'origin' => 'Expense'
));
$adminUser = Sentry::getUserProvider()->findByLogin('admin#admin.com');
Transaction::create(array(
'account_id_in' => $accountIn->id,
'account_id_out' => $accountOut->id,
'amount' => 300.00
));
}
}
I feel really stupid but instead of calling out use App\Models you would call out use App\Models\Account and it works as it should.
Then remember to run php composer.phar dump-autoload
I've had similar issues and prefixing my classes with the namespace operator solved them.
Try \Account