passing two parameter in form cant seem to figue out - php

Basically I have an event ID and User ID i need to pass in the form to store... however when i hit create it comes up with
Route pattern "/roles/{id}/{{id}}" cannot reference variable name "id" more than once.
However if i hit enter in the URL bar it works... so not to sure whats happening here... help would be greatful here the code.
Route file
// POST Add Users Race
Route::post('racehistory/{event_id}/store/{user_id}/race/', 'racehistoryController#store');
// GET Current Races
Route::get('events/currentRace', 'racingeventController#viewCurrentRace');
// GET Users
Route::get('events/{event_id}/users', 'racingeventController#users');
// GET Users with Group ID
Route::get('events/{event_id}/{group_id}', 'racingeventController#grouped');
// GET Add Users Race Form
Route::get('events/{event_id}/user/{user_id}/addrace', 'racingeventController#addUserRace');
// Add User to Event
Route::get('events/{event_id}/user/{user_id}', 'racingeventController#addUserToEvent');
// DELETE Remove User from Race Event
Route::get('events/{event_id}/delete/user/{user_id}', 'racingeventController#deleteUserToEvent');
// DELETE Race Event
Route::get('events/delete/{event_id}', 'racingeventController#destroy');
Route::resource('events', 'racingeventController');
Form View
{{ Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('racehistoryController#store', $user->id, $event->id))) }}
Controller - racehistoryController
public function store($event_id, $user_id)
{
$rules = array(
'start_event' => 'required',
'end_event' => 'required',
'pool_type' => 'required|max:3|min:3',
'name' => 'required|max:35|min:3',
'location' => 'required|max:35|min:3',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return 'form works';
}
}

Name your route:
Route::get(
'racehistory/{event_id}/store/{user_id}/race/',
['as' => 'store', 'uses' => 'racehistoryControlle#store']
);
Fix Form::open() helper:
{{
Form::open([
'class' => 'form-horizontal',
'method' => 'post',
'route' => ['store', $user->id, $event->id]
])
}}

Related

Laravel 9: testing get profile (by slug) for created row

I wrote test:
public function test_hello_world(){
$test = User::create(['name' => 'Test',
'email' => 'test#test.com',
'password' => 'password',
]);
Profile::create([
'user_id' => $test->id,
'name' => 'Test',
'slug' => 'test'
]);
$this->get('/profile/test')
->assertStatus(200);
}
What this code should testing? After get to this url it should display details about profile. If profile with this slug doesn't exist, we have error 404. In this test I create user and profile table (this 2 tables is connection) but after run test I have the error:
Expected response status code [200] but received 404. Failed
asserting that 200 is identical to 404.
Why I have this error since I created profile with this slug? For me the best option will be create testing database with a lot of records and conduct all test on it. Is it possible? How do that?
#Edit
I have a route and controller's method which display user's profile. If I go (in web browser) to localhost/profile/slug, it works, if this profile exist. My controller's method look like this:
public function show($slug) {
$profile = Profile::where('slug', $slug)
->firstOrFail();
return Inertia::render('Profile/Single', [
'profile' => $profile,
]);
}
And route:
Route::get('/profile/{slug}',
[ProfileController::class, 'show'])
->name('profile.show');
According to your requirement you have to create route for getting profile from slug name. You did wrong in single function. Without creating route it will not worked.
So below example may work for you.
For example:-
For creating data
public function createData(){
$user = User::create(['name' => 'Test',
'email' => 'test#test.com',
'password' => 'password',
]);
Profile::create([
'user_id' => $user->id,
'name' => 'Test',
'slug' => 'test'
]);
return redirect()->back()->with('success', 'Data created');
}
For Getting Data
public function getDataBySlug($slug){
$profile = Profile::where('slug',$slug)->firstOrFail();
return redirect('/dashboard')->with('slug', $slug);
}
In route file
you have to mention table name and column name {profile:slug} instead of id
Route::get('/profile/create', 'Controller#createData');
Route::get('/profile/{profile:slug}', 'Controller#getDataBySlug');
Your route definition is wrong please do as above

Method Illuminate\Validation\Validator::validateFiles does not exist. Laravel 5.8 submit form

This is most likely a duplicate question but I have been looking for solutions and can't seem to find one that fixes the issue I have. I have created a function called validateRequest which validates all the fields. This function is then called in store function $post = Post::create($this->validateRequest()); I have made sure in the HTML form enctype="multipart/form-data" has been included, but every time a submit a new entry that errors appear. Not sure if I am using the return tap method correctly or something else, really appreciate some help thanks.
public function validateRequest()
{
return tap(
$validated = request()->validate([
'title' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
'content' => 'required|string',
'active' => 'integer'
]), function () {
if (request()->hasFile('image')){
request()->validate([
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
]);
}
// Check if active is ticked
$validated['active'] = isset(request()->active[0]) ? 1 : 0;
// Create slug from title
$validated['slug'] = Str::slug(request()['title'], '-');
});
}
"files" is not a valid validator, use file without "s"
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
Hope this helps

laravel model binding for new record

i use model binding for profile update like this :
{{ Form::model($profile, [
'route' => [
'client.update'
,$profile->user_id
]
, 'method' => 'POST'
, 'class' => 'form-horizontal'
])
}}
but if the user has no profile information than the page get error because of :
$profile->user_id cos it does not exist in db
what can i do now ?
if the user has profile it could be update but not it could be save
{{ Form::model($profile, [
'route' => [
($profile->exists)
? 'client.update', $profile->user_id
: 'client.create'
]
, 'method' => 'POST'
, 'class' => 'form-horizontal'
])
}}
If the profile exists you know it's an existing record, so you can choose another route (and also another HTTP method. Typically you post for creation and put for update.)

Laravel Session Flash persists for 2 requests

Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with Session::flash.
when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator:
my code in UsersController:
function getCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController#postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
return View::make('layouts.form', $config);
}
function postCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController#postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
return View::make('layouts.form', $config);
}
return View::make('layouts.form', $config)->withErrors($validator->messages());
}
in form.blade:
#if ( $errors->count() > 0 )
<div class="alert alert-danger">
<p>The following errors have occurred:</p>
<ul>
#foreach( $errors->all() as $message )
<li>{{ $message }}</li>
#endforeach
</ul>
</div>
#endif
in master.blade:
#if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissable"> {{ Session::get('message') }}</p>
#endif
Maybe I'm not alone with this issue, here is another unanswered question.
Update
For anyone in future facing this problem:
Never flash session data without redirecting.
My code now looks like this:
function postCreateUser(){
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
} else {
Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
Session::flash('alert-class', 'alert-danger');
}
return Redirect::action('UsersController#getCreateUser');
}
You are Flashing session data and creating a view instead of redirecting, meaning the message will Flash for this request and for the next one, showing twice.
If you want to show the message on the current request without redirecting, I would suggest providing the errors to your View::make instead of trying to Flash the messages. If you MUST Flash the message on the current request, then you will need to Session::forget('key') or Session::flush() after your view.
The following seems to be available from version 5.1 onward. It used to be undocumented, now it is: see Laravel's session documentation.
session()->now()
This is the same as flash, except it won't persist to the next request.
As #Drew said earlier
You are Flashing session data and creating a view instead of
redirecting, meaning the message will Flash for this request and for
the next one, showing twice.
An easy way to flash a message once when you are creating a view is:
Session::flash($key, $value);
Session::push('flash.old', $key);
Happy coding!
I had a similar problem, but I couldn't use Return::redirct, as I was using Ajax to to post to and from a within a set of Tabs.
Therefore, I was calling
Input::flashExcept('_token');
only if the validation failed and returning a view with the old input. Assuming validation passed and I wanted to run some functions and create a new view based on new data, I would call:
Session::forget('_old_input');
I would put this before my final View::make
Hope this helps (or makes sense)...
create:
$request->session()->flash('status', 'Task was successful!');
delete:
$request->session()->forget('status');
Check the scope of your Api's both session put and session get Api's have to be in same scope(i e web.php or api.php).
A good method to repopulate form with old data:
Controller:
View::make( 'view.name' )->withOldFormData( Input::all() );
View:
{{ Form::model( $old_form_data ) }}

Laravel 4 - form refuses to show anything but blank page

Ok, so I am working on a test site while learning Laravel 4. This is my first MVC framework of any kind so I'm taking it slow.
I've already implemented several features including: Users (via Sentry), Profile (Users updating their own information), and all of that works fine.
Now, I am working on a system that allows users to request a quote for services. I felt like I understood the basic concepts behind forms and handling input, but apparently not. I was able to get the validation and everything out of the way, and all of that works. But now, when I go to actually execute the action (once the form data is validated), I am constantly given a blank page. I've tried pretty much everything.
Here is my QuoteController
public function create()
{
$user = Sentry::getUser();
if(!isset($statusMessage)) $statusMessage = "";
if(!isset($allErrors)) $allErrors = "";
return View::make('quote.create')->with(array('user' => Sentry::getUser(), 'statusMessage' => $statusMessage, 'allErrors' => $allErrors));
}
public function createDo()
{
$user = Sentry::getUser();
$input = Input::all();
$rules = array('quote_type' => 'required|in:web,design,other', 'budget' => 'required|in:1000,2000,5000,10000,20000,99999', 'sites_like' => 'max:5000', 'sites_dislike' => 'max:5000', 'content' => 'required|max:50000');
$filesrules = array('file' => 'mimes:jpeg,png,pdf,doc,txt,bmp,gif|max:500');
$validator = Validator::make($input, $rules);
if($validator->fails())
{
$allErrors = $validator->errors();
}
if(Input::hasFile('files'))
{
$files = Input::file('files');
if (!is_array($files))
{
$files = array($files);
}
foreach($files as $file)
{
if (!is_a($file, 'Symfony\Component\HttpFoundation\File\UploadedFile')) {
continue;
}
$fileValidator = Validator::make(array('file' => $file), $filesrules);
if($fileValidator->fails())
{
$messages = $fileValidator->messages()->toArray();
foreach($messages['file'] as $message)
{
$allErrors->add('file', $message);
}
}
}
}
if($allErrors->any())
{
Input::flash();
return Redirect::route('quote-create')->withErrors($allErrors)->withInput();
}
else
{
Quote::create(array(
'status' => 1,
'public_id' => strtoupper(substr(md5(rand(100000000,3888888888).time()), 0, 10)."-".substr(md5(rand(100000000,3888888888).time("a week ago")), 0, 10)),
'customer' => intval($user->id),
'quote_type' => $input['quote_type'],
'sites_like' => $input['sites_like'],
'sites_dislike' => $input['sites_dislike'],
'budget' => intval($input['budget']),
'content' => $input['content']));
return Redirect::route('quote');
}
}
And here's the routes
// Quote
Route::get('/quote', array('before' => 'auth|quote', 'uses' => 'QuoteController#index', 'as' => 'quote'));
Route::post('/quote/create', array('uses' => 'QuoteController#createDo', 'as' => 'quote-createDo'));
Route::get('/quote/create', array('before' => 'auth', 'uses' => 'QuoteController#create', 'as' => 'quote-create'));
// Staff
Route::get('/staff', array('before' => 'auth.staff', 'uses' => 'StaffController#index', 'as' => 'staff-index'));
// Sandbox
Route::get('/sandbox', array('before' => 'permission:user.create', function()
{
return "You have access!";
}));
And finally, the quote.create view.
{{ $errors }}
{{ $statusMessage }}
<br/><br/>
{{ Form::open(array('route' => 'quote-createDo', 'files' => true)) }}
<br/><br/>
<label for="quote_type"><span>Type of Quote</span></label>
{{ Form::select('quote_type', array('web' => 'Web', 'design' => 'Design', 'other' => 'Other')) }}
<br/><br/>
<label for="budget"><span>Project Budget</span></label>
{{ Form::select('budget', array('1000' => 'Up to $1,000', '2000' => '$1,000 - $2,000', '5000' => '$2,000 - $5,000', '10000' => '$5,000 - $10,000', '20000' => '$10,000 - $20,000', '99999' => 'Over $20,000')) }}
<br/><br/>
<label for="sites_like"><span>Three designs you like</span>List three websites or designs that you like, and why - in regards to design, formatting, graphics, anything. This will help us understand your tastes and give us a jumping-off point for your project.</label>
{{ Form::textarea('sites_like') }}
<br/><br/>
<label for="sites_dislike"><span>Three designs you don't like</span>Along the same lines, give us three examples of desgins or websites that you don't like.</label>
{{ Form::textarea('sites_dislike') }}
<br/><br/>
<label for="content"><span>The Meat</span>Explain to us, as best as you can, what you need us to do.</label>
{{ Form::textarea('content', '',array('class' => 'big')) }}
<br/><br/>
<label for="files[]"><span>File Upload</span>Upload any files here that might help us understand your needs better. (Diagrams, sketches, logos, etc.)</label>
{{ Form::file('files[]', array('multiple'=>true)) }}
<br/>
<br clear="all">
<br/><br/>
{{ Form::submit('Submit Quote', array('class' => 'submit')) }}
{{ Form::close() }}
Thank you very much for any and all help!
Joe

Categories