Laravel create new records error - laravel

I have a few Form on create different records with different validation rules.
My route (web.php) file:
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/home/info/create/{id}', 'InfoController#create');
Route::post('/home', 'InfoController#store')->name('home');
Route::get('/home/info/delete/{id}', 'InfoController#delete');
Route::get('/home/odbor/create/{id}', 'OdborController#create');
Route::post('/home', 'OdborController#store')->name('home');
Route::get('/home/odbor/delete/{id}', 'OdborController#delete');
Route::get('/home/zamestnanec/create/{id}', 'ZamestnanecController#create');
Route::post('/home', 'ZamestnanecController#store')->name('home');
Route::get('/home/zamestnanec/delete/{id}', 'ZamestnanecController#delete');
Route::get('/home/program/create/{id}', 'ProgramController#create');
Route::post('/home', 'ProgramController#store')->name('home');
Route::get('/home/program/delete/{id}', 'ProgramController#delete');
});
Creat, store, delete function :
(function is simillar in all controller)
public function create(Fakulta $id)
{
return view('create.info', compact('id'));
}
public function store(CreateInfoRequest $request)
{
Info::create($request->all());
return redirect('home');
}
public function delete($id)
{
Info::where('id',$id)->delete();
return redirect('home');
}
And problem is, when I want create new e.g. Info (/home/info/create) after touch submite button I get validation errors. On validation is using file specified in last Controller from middleware group (ProgramController#store) and I don't know why. But when I move Route::post('/home', 'InfoController#store')->name('home'); on last line of group or create new program (/home/program/create) everything is OK.
Easier:
After touch submit button is dont use this file
CreateInfoRequest.php file:
public function rules()
{
return [
'title' => 'required',
'description' => 'required',
'event_date' => 'required|date|after:today'
];
}
but this one :
CreateProgramRequest.php
public function rules()
{
return [
'title' => 'required',
'titul' => 'required',
'length' => 'required',
'forma' => 'required',
'typ'=> 'required',
'description' => 'required',
'fakulta_id' => 'required',
];
}

You should try with below changes:
Put route as:
Route::post('/home/info/store', 'InfoController#store')->name('infoStore');
Instead of
Route::post('/home', 'InfoController#store')->name('home');
Because you create same post route for all so just change route and try its may be solve your problem.

Related

Undefined method 'posts' inside controller - Laravel

I am getting error for undefined method which is defined inside my User model.
My controller:
$inputs = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
auth()->user()->posts()->create($inputs);
My Post model:
public function user() {
return $this->belongsTo('App\Models\User');
}
My User model:
public function posts() {
return $this->hasMany('App\Models\Post');
}
correct your relationship
public function posts() {
return $this->hasMany(Post::class);
}
First your posts relationship is wrong, it must be hasMany NOT belongsTo
public function posts() {
return $this->hasMany(User::class);
}
Then it should work.
You can also try to create the model in a different way:
$validated = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
// Here you should check if $validated has all required fields
// because some could fail, in that case aren't in the array
Post::create([
'title' => $validated['title'],
'user_id' => auth()->id, // or auth()->user->id
'post_image' => $validated['post_image'],
'body' => $validated['body'],
]);
Laravel Validation Docs

Should I use prepareForValidation of FormRequest to passing params for validation request?

I want to pass user_id and post_id to formRequest. So I use prepareForValidation to merge to the request like that done in the code below. Is that way ok or I should be passing params on Controller?
public function rules()
{
return [
'content' => 'required',
'user_id' => 'required|exists:\App\Models\User,id',
'post_id' => 'required|exists:\App\Models\Post,id'
];
}
public function prepareForValidation()
{
$this->merge([
'user_id' => Auth::user()->id,
'post_id' => $this->post->id
]);
}
I think it's ok but remove unneeded checks like:
exists:\App\Models\User,id,
and
exists:\App\Models\Post,id
I think all you need to make it
public function rules()
{
return [
'content' => 'required',
'user_id' => 'required',
'post_id' => 'required'
];
}
To avoid hitting the database for no reason the user is the current user so no need to check and the post in the current request so it can not be deleted.
Note:
(The business may be different for the post based on your project. I mean may admin can delete it so the normal user can not do the action then keep this rule for post_id (exists:\App\Models\Post,id) )
If Route look like
Route::patch('posts/{post}', 'update');
public function rules()
{
return [
'content' => 'required'
];
}
public function prepareForValidation()
{
$this->merge([
'user_id' => auth()->id(),
'post_id' => $this->route('post')->id
]);
}
M too late but here is a smart way.
Before validation code in controller just use below 2 methods.
1: $request->request->remove('field_name');
2: $request->request->add(['field_name' => 'modified_value']);
Good to go.

Call to undefined method App\User::events()

I am trying to store data into the database, but the error I'm getting is:
Call to undefined method App\User::events()
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$request->user()->events()->create($request->all());
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Try this:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$user = User::create($request->all()); // create the user
event(new UserRegistered($user)); // Add your own event class name.
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Note: Assuming that you have created the UserRegistered event. And call it by event helper method.
It seems like you do not have any events() relationship in you User model.
Assuming you have Event model, you can write like in User model:
public function events()
{
return $this->hasMany(Event::class);
}

Laravel - Can't upload the user in multiauth system

I am using multi auth login system. I made register, login and mail system. But i don't know how to make update function. Every member needs to update own profile. My problem is i can't get the related users details. id, name, etc...
In my auth.php customer guards was created:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
]
Also this is the CustomerLoginController:
class CustomerLoginController extends Controller{
public function __construct()
{
$this->middleware('guest:customer')->except('logout', 'userLogout');
}
public function showLoginForm(){
return redirect()->route('homepage');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('homepage'));
}
return redirect('/')->with('error_login', 'Login Fail');
}
public function logout(Request $request) {
Auth::guard('customer')->logout();
return redirect('/');
}
I added the function show($id) and function update(Request $request)
But as i told. Can't get the related user.
My last try is:
$user = Customer::find($id);
this is the right way to doing this i think. But i can't connect them.
ps: i am not using --resources (crud). I must do that manually.

Defining custom error messages in controller in Laravel 5.2

I need to do validation in one of my controllers — I can't use a request class for this particular issue — so I'm trying to figure out how to define custom validation messages in the controller. I've looked all over and can't find anything that suggests it's possible. Is it possible? How would I do it?
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// Can I create custom error messages for each input down here? Like...
$this->validate($errors, [
'title' => 'Please enter a title',
'body' => 'Please enter some text',
]);
}
You should have a request class like below. message overwrite is what you are looking for.
class RegisterRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'UserName' => 'required|min:5|max:50',
'Password' => 'required|confirmed|min:5|max:100',
];
}
public function response(array $errors){
return \Redirect::back()->withErrors($errors)->withInput();
}
//This is what you are looking for
public function messages () {
return [
'FirstName' => 'Only alphabets allowed in First Name',
];
}
}
This did it
$this->validate($request, [
'title' => 'required',
'body' => 'required',
], [
'title.required' => 'Please enter a title',
'body.required' => 'Please enter some text',
]);

Resources