BadMethodCallException in Macroable.php line 74: Method validate does not exist - php

I'm getting little bit issue in laravel 5.2
When i submit data throgh post. data found in request but not save. pls help.
https://www.awesomescreenshot.com/image/3111642/0ec1946875e85f53eaec7970483ff5f0
Customer.php
<?php
namespace App\Http\Controllers;
enter code here
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Customer extends Controller {
public function index() {
//$members = Customer::latest()->paginate(10);
return view('pages.admin.customers.customers', compact('customers'));
// ->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
return view('pages.admin.customers.create');
}
public function store(Request $request) {
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
Customer::create($request->all());
return redirect()->route('customer.index');
}
}
Model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = [
'firstname', 'lastname'
];
protected $table = 'customers';
}

You have a mistake in validation, instead of:
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
You need use:
$this->validate($request, [
'firstname' => 'required',
'lastname' => 'required',
]);
There are other ways to validate which you can read about in official documentation Validation.

Related

Spatie assignRole not working (Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync())

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.

Why Method App\Http\Controllers\RegisterController::guard does not exist and MemberExtra table not fill with data in laravel

thanks for helping
I have some error when insert data i nto database, that is guard does not exit when I try to register by using this controller
namespace App\Http\Controllers;
use App\Models\MemberExtra;
use App\Models\User;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function index(){
return view('users.register');
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'referrer_id' => 'required',
'position' => 'required',
'username' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$ref_id = $data['referrer_id'];
$poss = $data['position'];
$posid = getLastChildOfLR($ref_id,$poss);
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referrer_id' => $data['referrer_id'],
'position' => $data['position'],
'username' => $data['username'],
'join_date' => Carbon::today(),
'posid' => $posid
]);
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
MemberExtra::create([
'user_id' => $user['id'],
'left_paid' => 0,
'right_paid' => 0,
'left_free' => 0,
'right_free' => 0,
'left_bv' => 0,
'right_bv' => 0,
]);
updateMemberBelow($user['id'], 'FREE');
return $this->registered($request, $user) ?: redirect()->route('home');
}
}
when register , show this error
and I refresh the page , user data is inserted into database but MemberExtra data still not insert
And this guard does not exist error happen again and again whenever register.
How can fix this error
Can someone help me
In your controller I didn't see the RegistersUsers trait which have guard function.
You have missed to write below in your controller. By default this function exist in RegistersUsers this trait
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('your guard name');
}

FormRequest message in laravel 8 not show messages

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',
]
}

Laravel 5.5: Execute a method before registration

I'm using the default laravel authentication. Every user who registeres in my site needs a activation pin. The valid PINs are stored in a different table. Whenever a user registeres, I want to test if the PIN is valid or not. So, is there any method that I can override in RegisterController that executes before regstering the user?
Yes. You can override protected register method in RegisterController. This is a simple solution. I do this to validate params, save a new user, and force return JSON in one of my projects.
For example:
protected function register(Request $request)
{
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'phone' => 'required',
'pin' => 'required'
]);
//Check your PIN here, if it's wrong, append errors array
if ($validator->fails())
throw new ValidationFailed($validator->errors());
User::create([
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
]);
return ResponseJSON::make(trans('responses.registered'));
}
You can add a validation rule for validating the pin in the validator method like this :
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'pin' => [
'required',
Rule::exists('pins')->where(function ($query) {
$query->where('Some condition');
}),
],
]);
}
I assume you have a table for pins called pins
extend the register function in user class:
public function register(Request $request)
{
event(new \App\Events\NewUserRegistered(Auth::user()));
return redirect($this->redirectPath());
}
NewUserRegistered:
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\User;
class NewUserRegistered extends Event
{
use SerializesModels;
public $userID;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $userID)
{
//get whatever is massed in here's value in the id column
$this->id = $userID;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return [];
}
}

FatalThrowableError Laravel 5.2

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']);

Categories