Laravel 8 default RegisterController. Pass parameters in array - laravel-8

I'm trying to create a form for register a user with a Vue component.
I want to use the default routes generated by Auth::routes(); and the default "create" function by the default RegisterController from Laravel 8
This is the create() function I see on RegisterController but it doesn't seem the function that the route is calling.
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
But this is the created route:
|POST| register| generated::RuTERdEs1GA9zWNu | App\Http\Controllers\Auth\RegisterController#register| web
Why do I have a create() function if the route points to "register"? What's the function this "register" is actually calling?

The register method is actually part of the Illuminate\Foundation\Auth\RegistersUsers; trait. This is where the validation is called, the user is created, the Registered event is fired and the user is logged in.
It was set up this way to abstract so that the bits your most likely to change are easily available but the other parts of the code which are more essentially/less likely to need updating aren't "cluttering" your controller.

Related

Cakephp 3.7.x How to retrieve user data? using Authentication component

I am using cakephp 3.7.2 with Authentication component
$user = $this->Authentication->getIdentity();
prints:
object(Authentication\Identity) {
'config' => [
'fieldMap' => [
'id' => 'id'
]
],
'data' => object(App\Model\Entity\User) {
'id' => (int) 1,
'email' => 'aa.aaa#gmail.com',
...
}
}
I have tried $user->data but it doesn't work.
How to print user data?
Authentication Component
So I have figured it out.
In User Entity class
Add use Authentication\IdentityInterface;
and then implement the IdentityInterface.
class User extends Entity implements IdentityInterface
{
blablabla...
yale yale yale ...
Now you can print:
$user = $this->Authentication->getIdentity();
debug($user->id);
As per Authentication component documentation
The identity object is returned by the service and made available in
the request. The object provides a method getIdentifier() that can be
called to get the id of the current log in identity.
You can use this accordingly as below to get the user data:
// Service
$identity = $authenticationService
->getIdentity()
->getIdentifier()
// Component
$identity = $this->Authentication
->getIdentity()
->getIdentifier();
// Request
$identity = $this->request
->getAttribute('identity')
->getIdentifier();
The identity object provides ArrayAccess but as well a get() method to
access data. It is strongly recommended to use the get() method over
array access because the get method is aware of the field mapping.
For eg. to access email and username from the identity you can use the below code.
$identity->get('email'); // to access email
$identity->get('username'); // to access username
Reference link: Authentication -> Docs -> Identity Object
Hope this will help.
I´m using AuthComponent in CakePHP 4.xxx.
I can get User data i.e. in a view with
$user = $this->getRequest()->getAttribute('identity');
I found the Information on: http://gotchahosting.com/blog/category/cakephp/4002624
Maybe it helps someone who is looking for information about this in CakePHP4

method file returnsMethod Illuminate\Http\Response::file does not exist

i am trying to send a file with my API response to postman
return response($company)->file($company->logo, $company->main_photo);
laravel woops returns:
Method Illuminate\Http\Response::file does not exist.
what am i doing wrong?
I think you do not need to retrieve a file using the response helper method.
it just needs to send file location to the front-end, e.g. let assume your $company object shape is something like:
{
id: 1234,
name: 'My Company',
logo: 'images/companies/logo/1425.jpg'
}
then it is enough to pass above object to your front-end and in a contract ask your front end to put http://example.com/files/ at the beginning of file address then or you may define a JsonResource class and override the logo path with the absolute address (append base-URL to the beginning).
it might look like:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ComapnyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'logo' => 'https://example.com/file/' . $this->logo,
];
}
}
Take a look the documentation.

Where and how to set an SQL request for a form element?

I read a lot of things of things in the cookbook or on stackoverflow but I can't find something adapted and clearly explained about how to solve my problem.
I have an SQL request that allows me to find schools that teaches a specific subject. I need to set this SQL request so that when I load the page containing my form, the request is done and I see the result (a list of school) in a multi select form. My best guess is that I need to set it inside my controller, but then again, I'm not even sure of that since it's the first time that I need to do that
I don't know if I should show you any code, so ask if you need to see something!
Thank you in advance
edit Here is my formType
<?php
namespace MissionBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use SocieteBundle\Entity\Societe;
class PublicType extends AbstractType{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('public')
->add('ecolesDispo')
// My goal is to replace 'ecolesDispo' (that is currently a one-to-many)
// by my SQL request.
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MissionBundle\Entity\Mission'
));
}
}
Surely not in the controller. You need to use the "query_builder" attribute when you add the field to the form. Take a look at this example, from the Symfony cookbook : http://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities
And you should translate your raw SQL query into DQL, so it's database-agnostic.
UPDATE about using a query builder with native SQL : http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/native-sql.html#the-nativequery-class
So something like this following piece of code should work (you'll have to edit some property names and fill the query though)
$builder->add('ecolesDispo', EntityType::class, array(
'class' => 'AppBundle:Ecole',
'query_builder' => function (EntityRepository $er) {
return $er->createNativeQuery('SELECT * FROM ecoles WHERE [...]');
},
'choice_label' => 'title',
));

Laravel 5.2 : How to call "sendFailedLoginResponse" from custom Login Event Handler?

In Laravel 5.2, there is a function already overriden in my AuthController.php:
public function sendFailedLoginResponse()
{
$errors = new MessageBag([
'email' => ['Error message for email'],
'password' => ['Error message for password'],
'mycustominput' => ['Error message for my custom input field'],
]);
return redirect()->back()->withErrors($errors);
}
This alone works (like magic) via normal FAILED login attempts. (When login is failed, the login form already shows this custom error messages, instead of the default ones. So this is getting triggered. So is ok.)
Now i have below Custom Login Event Handler, registered in the EventServiceProvider.php:
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn']
And then, i wanna TRIGGER the overridden function sendFailedLoginResponse() from this Custom Login Event Handler. Something like:
app/Listeners/UserLoggedIn.php:
// Some codes at top
public function handle(Login $event)
{
// Some coding ..
// Some custom verifications ..
if ( $customLoginCheck == false )
{
????::sendFailedLoginResponse(); // <----- Here call/trigger the method!
}
}
When i tried using Auth::sendFailedLoginResponse(), it gives me following errors:
ErrorException in AuthManager.php line 288:
call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\SessionGuard' does not have a method 'sendFailedLoginResponse'
Because i do NOT know "how" to call that desired function from a Custom Event Handler. (And also don't know what are the required includes.)
Please help to suggest. (Thanks all)

Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable error in laravel 5

I’m building a carpool app where its the intention that when a user registers they’re able to fill in they have a car however this car is in a table on its own.
When I try to create it with the field checkt I get this error:
Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Cars given, called in /home/vagrant/Code/carpool-app-going-your-way/www/vendor/compiled.php on line 2078 and defined
Any ideas on how to fix it?
Here is my code:
registrar.php
public function create(array $data)
{
if (isset($_POST["ihaveacar"])){
return Cars::create([
'seats'=>$data['seats'],
'seats_taken'=>'0',
]);
}
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'screen_name' => $data['screen_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'route' => $data['route'],
'state' => $data['state'],
'description' => $data['description'],
'license_since' => $data['license_since'],
]);
}
User.php
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends model implements AuthenticatableContract, CanResetPasswordContract{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['first_name', 'last_name', 'screen_name', 'email', 'password', 'birthday', 'license_since', 'kilometers', 'state', 'route','image','description','soft_delete', 'is_admin'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
use SoftDeletes;
protected $dates = ['deletec_at', 'created_at', 'updated_at'];
}
Any ideas how to fix this?
Thanks in advance
Edit: all of a sudden it seems to be running without errors. I don’t get it.
you should extend Illuminate\Foundation\Auth\User
like
use Illuminate\Foundation\Auth\User as AuthUser;
class Member extends AuthUser
{
public $table='members';
protected $fillable = ['name', 'password','qq','phone'];
}
You're passing an instance of App\Cars to the registrar via the create() method. Remove all non-login logic from the registrar and only perform said logic after the authentication logic is actually complete.
You’re returning two different object types in your create() method. If the request has a parameter called ihaveacar then you return a Car instance, otherwise you return a User instance. You need to make your mind up what your create() method should actually return.