I have two model that are related.
Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'city',
'post_code',
'street',
'country'
];
protected $hidden = [
'created_at',
'updated_at',
'addressable_id',
'addressable_type'
];
public function addressable(): MorphTo
{
return $this->morphTo();
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Club extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'phone',
'description',
'user_id'
];
protected $hidden = [
'created_at',
'updated_at'
];
public function address()
{
return $this->morphMany(Address::class, 'addressable');
}
}
For that models i've got Request class with validator rules.
Requests
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreAddressRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'city' => 'required|string|max:125',
'post_code' => 'required|string',
'street' => 'required|string',
'country' => 'required|string| max:125'
];
}
}
<?php
namespace App\Http\Requests;
use App\Traits\FailedValidation;
use Illuminate\Foundation\Http\FormRequest;
class StoreClubRequest extends FormRequest
{
use FailedValidation;
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|max:125',
'description' => 'required|string',
'email' => 'email:dns',
'phone' => 'string|max:125',
// 'address' => (new StoreAddressRequest)->rules(), ???
'images' => 'required|image'
];
}
}
Trying to create new club with address.
I'm sending request to API like that:
[
"name":"dfsdf",
"dsfsdf":"sdfsdf",
"address": {
"city": "name",
"post_code":"46-454"
}
]
Address may be added standalone or from other model that are related too.
Now only fields from club request are validated.
How to validate club and address request?
Related
Spatie user role permissions not working
Here is my RoleController.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
public function saveUserRoles(Request $request)
{
$validator = Validator::make($request->all(), [
'role_name' => 'required|string|unique:roles,name',
]);
if ($validator->fails()) {
alert()->error(trans($validator->messages()->all()[0]));
return back();
}
$role = new Role;
$role->name = $request->role_name;
$role->guard_name = config('auth.defaults.guard');
$role->save();
alert()->success(trans('New Role Created Successfully!'));
return redirect()->route('admin.add.user.roles');
}
User Model
User.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes, HasApiTokens;
use HasRoles;
protected $fillable = [
'user_id', 'profile_image', 'name', 'email', 'address','phone','location','role_id','auth_type', 'password','status'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsToMany(Role::class, 'role_id');
}
}
UserController
UserController.php
use Spatie\Permission\Models\Role;
use App\Http\Requests\UserCreateRequest;
public function saveUser(UserCreateRequest $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role_id' => $request->role_id,
'status' =>0,
]);
$role = Role::find($request->role_id);
$user->assignRole([$role->name]);
}
When i try to create a new user it shows an error
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync()
Here only need role option without any permissions
Here is your solution, as given in the documentation.
I'm doing something wrong?
My If (Auth::attempt($validated)) {} always fails when I change default user. But work with default user. Maybe i forgot any config in my new user 'personal'?
config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Personal::class,
],
App/Models/Personal.php
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Personal extends Authenticatable
{
use HasFactory;
protected $table = 'personals';
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
App\Http\Requests\AuthRequest.php
use Illuminate\Foundation\Http\FormRequest;
class AuthRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required'
];
}
}
App\Http\Controller\AuthController.php
public function login(AuthRequest $request)
{
$validated = $request->validated();
if ($validated) {
\Log::info($validated); //<- so far it works
if (Auth::attempt($validated)) { //<- this if always fails with personal model, but it work with default user model
\Log::info('test');
$personal = Auth::user();
return redirect()->route('dashboard');
}
return redirect()->back()->withInput()->withErrors(['algo deu errado']);
}
return redirect()->back()->withInput()->withErrors(['Preencha todos os campos']);
}
$validated = [ 'email' => 'teste#outlook.com', 'password' => 'teste123', ];
In my laravel 8 app I am trying to create two files CreateUserRequest and updateUserRequest to use personalized validations.
In the method rules I´m calling my model's variable $createRules but when I send my form, this don´t send, don´t show messages, error... Nothing.
I have attached CreateUserRequest, my model and controller's store method:
CreateUserRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Models\User;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return User::$createRules;
}
}
Model
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'surname',
'experience',
'skills',
'education',
'location',
'profesion',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static $createRules = [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|min:4|max:10|confirmed',
];
public static $updateRules = [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
];
}
Controller's store method
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\Role;
use App\Models\User;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic as Image;
use JamesDordoy\LaravelVueDatatable\Http\Resources\DataTableCollectionResource;
use Prettus\Validator\Exceptions\ValidatorException;
public function store(CreateUserRequest $request)
{
try {
$data = array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => password_hash($request->get('password'), PASSWORD_BCRYPT),
'api_token' => Str::random(60),
);
$user = User::create($data);
$roles = $request->get('roles');
// We assign the Client's role
if(empty($roles)) {
$user->assignRole(2);
} else {
foreach($roles as $rol){
$user->assignRole($rol);
}
}
} catch (ValidatorException $e) {
Flash::error($e->getMessage());
}
Flash::success('This is a message!');
return redirect()->route('users.index');
}
In the blade I have #include('flash::message') for getting flashed messages, and this view it´s included in other #include('admin.layouts.alertMessage').
I don´t know what I am doing wrong.
Thanks for help me and sorry for my bad English.
UPDATED
my problem i think that i don´t arrive to my controller. I´m doin echo in my function with one exit and load all my page without message echo
attach my form and my routes:
<form action="{{ route('users.store') }}" method="POST">
#csrf
#include('admin.users.fields')
</form>
routes
/** USERS BLOQ ROUTES */
Route::resource('users', UserController::class);
TBH, i didn't know that you can get validation logic from their Model. My advice is just copy paste your validation logic to the request. Since Request is only for Validation purpose ( CMIIW )
CreateRequest
public function rules()
{
return [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|min:4|max:10|confirmed',
];
}
UpdateRequest
public function rules()
{
return [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
];
}
UPDATE
Just combine it to one Requests, give RequiredIf for password request, in case your update route contains update
use Illuminate\Validation\Rule;
...
public function rules()
{
return [
'password' => Rule::requiredIf(str_contains(url()->current(), 'update')) . '|min:4|max:10|confirmed',
]
}
I am trying to make register and log in in laravel 5.2, but am receiving
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, null given, called in /Applications/XAMPP/xamppfiles/htdocs/blogs/app/Http/Controllers/RegisterationController.php on line 30
Here is my registerationcontroller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class RegisterationController extends Controller
{
//
public function create(){
return view('sessions.create');
}
public function store(){
//validate form
$this->validate(request(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
//store the data
$user = User::create(request(['name','email','password']));
//login
auth()->login($user);
//redirect
return redirect()->home();
}
}
and here is the user model:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany(Post::class);
}
}
i am following video for laravel 5.4, not sure if this is the problem.
You are not passing an array to the function you are passing the result of a function called request() which probably does not exist.
So amend the call something like this
//$user = User::create(request(['name','email','password']));
$user = User::create(
[
$request->input('name'),
$request->input('email'),
$request->input('password')
]
);
or
$params = [ $request->input('name'),
$request->input('email'),
$request->input('password')
];
$user = User::create( $params );
or
User::create($request->only(['name','email','password']);
In Yii2 I trying to write a standalone validator, but it's doesn't work. Below my code:
Standalone validator:
namespace app\components;
use yii\validators\Validator;
class UsernameValidator extends Validator {
public function validateAttribute($model, $attribute)
{
$this->addError($model, $attribute, 'Test.');
}
}
Model code:
namespace app\models;
use Yii;
use yii\base\Model;
use app\components\UsernameValidator;
class SignUpForm extends Model {
public $username;
public $password;
public $confirmPassword;
public function rules(){
return [
[['username', 'password', 'confirmPassword'], 'required'],
['password', 'compare', 'compareAttribute' => 'confirmPassword', 'operator' => '=='],
['confirmPassword', 'compare', 'compareAttribute' => 'password', 'operator' => '=='],
['username', UsernameValidator::className(), 'skipOnEmpty' => false],
];
}
}
skipOnempty, skipOnError don't fix that problem. Please, who experienced this? help me fix.