I am using PHP Laravel framework. I am trying to save a form after submission. Strangely first time it is not saving, but subsequently, it is saving. On the first post request, the flow isn't even entering function save_application
Code below.
My controller:
class ApplicationController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['store_application']]);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function save_application(Request $request){
$user = Auth::user();
if(isset($request->application)){
$application = Application::where("user_id",$user->id)->first();
if($application){
$application->update($request->application);
}else{
$application = new Application;
$application = Application::create($request->application);
$application->user_id = $user->id;
$application->save();
}
}
return $this->store_application($request);
}
public function store_application(Request $request){
if(isset($request->application)){
if($request->session()->has('application')){
$request->session()->forget('application');
}
$application_data = [];
$application = new Application;
$application->attributes = $request->application;
$application_data["application"] = $application;
$request->session()->put("application" , $application_data);
}
//
return Redirect::to("/application")->withErrors(array("success"=>"Thank you for submitting the application"));
}
}
My routers
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('application');
My html
<form method="POST" action="/application" enctype="multipart/form-data" id='application_form'>
<input type="hidden" name="_token" value="xtQapusSjgf5XVUxjCOudedeH93a8hEqyfaNh8ChEaKt">
<input type='checkbox'>
<label>I've read and accept the terms and conditions</label>
<p class='font-size-16 font-bold text-uppercase text-black'>
Your information
</p>
<hr class='hr1'>
<div class='row form-group'>
<div class='col-lg-6'>
<label class='control-label'>First name*</label>
<input type='text' class='form-control' name='application[first_name]' value="">
</div>
<div class='col-lg-6'>
<label class='control-label' >Last name*</label>
<input type='text' class='form-control' name='application[last_name]' value="">
</div>
</div>
<div class='form-group'>
<label class='control-label' >Middle name</label>
<input type='text' class='form-control' name='application[middle_name]' value="">
</div>
<div class='form-group'>
<label class='control-label'>ID*</label>
<input type='text' class='form-control' name='application[]' value="">
</div>
<button class="btn btn-primary text-uppercase">Submit <i class='fa fa-check text-white'></i></button>
</form>
your routes have the same name, give them differents.
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('other');
and in your form, you can:
<form method="POST" action="{{ route('application') }}" enctype="multipart/form-data" id='application_form'>
and as senty say:
<button type="submit">
</form>
I think you overcomplicate things, you can simply use updateOrCreate() to make it cleaner.
First of all, make sure $fillable or $guarded is utilized in your Application model. (Application.php)
protected $fillable = ['each', 'field', 'as', 'string'];
// or
protected $guarded = [];
Some improvements for your method:
public function save_application(Request $request){
// 1. Do a proper check
$request->validate([
'application.first_name' => 'required',
'application.middle_name' => 'required',
'application.last_name' => 'required'
]);
// 2. Update or Create
$application->updateOrCreate(
[ 'user_id' => $user->id ],
$request->application // I suppose this is an array that you want
);
// 3. Handle the redirect the right way so you can eliminate the other `store_applcation()` method entirely
return redirect()->back()->with([
'application' => $application
'success' => "Your Message"
]);
}
Also you don't need store_application() method in your controller or its route because your html form is POST'ing to /application route.
This is what you want, right?
Related
How to suppress validation errors with a back button in Laravel ??
Details: I have form with two buttons and I made validation how to skip validation when click on (back-button)?
the code in the view page:
<form method="POST" action="{{route("movies.store")}}" class="mt-5 w-50 m-auto">
#csrf
<div class="mb-3">
<label class="form-label">Movie Name</label>
<input type="text" name="movie_name" class="form-control">
#error('movie_name')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Descrption</label>
<input type="text" name="movie_description" class="form-control">
#error('movie_description')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Gener</label>
<input type="text" name="movie_gener" class="form-control">
#error('movie_gener')
<span class="error">{{$message}}</span>
#enderror
</div>
<button type="submit" name="action" value="back" class="btn btn-warning me-3">Back</button>
<button type="submit" name="action" value="add" class="btn btn-primary">Add</button>
</form>
the code in the controller file:
public function store(MoviesFormRequest $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
$data = $request->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
If you just want to solve the problem by implementing back button instead of using button tag use anchor tag as follows
Back
And remove the switch statement and just do as follows:
public function store(MoviesFormRequest $request)
{
Movie::create($request->all());
return redirect()->route("movies.index");
}
Inside your MoviesFormRequest class do all the validations like :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MoviesFormRequest 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 [
'movie_name' => 'required',
'movie_description' => 'required',
'movie_gener' => 'required',
];
}
}
This will work for you just customize the anchor tag to look good. Hope this solve your problem.
The validation happens in your custom request (MoviesFormRequest) before the code in the controller method is executed.
So in order to skip validation given a specific request input, you have to make the it part of the switch block
use Illuminate\Http\Request;
// use the base request here (no validation at this point)
public function store(Request $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
// in our case block we can validate
$this->validate($request, [
'title' => ['required'],
//... your rules here
]);
$data = $this->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
I have edited the Rainlab User plugin to allow for the user to upload a file on the frontend attached to their user profile. Works in the backend but not working on the frontend.
Inside User.php Model
public $attachOne = [
'avatar' => 'System\Models\File',
'id_document' => 'System\Models\File'
];
/**
* #var array The attributes that are mass assignable.
*/
protected $fillable = [
'name',
'surname',
'login',
'username',
'email',
'password',
'password_confirmation',
'created_ip_address',
'last_ip_address',
'id_document'
];
Inside Account.php Component
public function onSubmit()
{
if (!$user = $this->user()) {
return;
}
$data = post();
if ($this->updateRequiresPassword()) {
if (!$user->checkHashValue('password', $data['password_current'])) {
throw new ValidationException(['password_current' => Lang::get('rainlab.user::lang.account.invalid_current_pass')]);
}
}
if (Input::hasFile('avatar')) {
$user->avatar = Input::file('avatar');
}
if (Input::hasFile('id_document')) {
$user->id_document = Input::file('id_document');
}
$user->fill($data);
$user->save();
/*
* Password has changed, reauthenticate the user
*/
if (array_key_exists('password', $data) && strlen($data['password'])) {
Auth::login($user->reload(), true);
}
Flash::success(post('flash', Lang::get(/*Settings successfully saved!*/'rainlab.user::lang.account.success_saved')));
/*
* Redirect
*/
if ($redirect = $this->makeRedirection()) {
return $redirect;
}
$this->prepareVars();
}
Inside update.htm component
<form data-request="onSubmit" data-request-files data-request-flash>
<input type="hidden" name="_handler" value="onSubmit">
{{ form_token() }}
{{ form_sessionKey() }}
<div class="form-group">
<label for="accountName">Full Name</label>
<input name="name" type="text" class="form-control" id="accountName" value="{{ user.name }}">
</div>
<div class="form-group">
<label for="accountEmail">Email</label>
<input name="email" type="email" class="form-control" id="accountEmail" value="{{ user.email }}">
</div>
<div class="form-group">
<label for="accountEmail">ID Document</label>
<input type="file" name="id_document">
</div>
<div class="form-group">
<label for="accountEmail">Avatar</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
Result in system_files table when I submit the form
Database return
How do I make sure it adds all needed details in order to upload the file. Even the storage does not reflect the file on upload.
i am a begineer of codeigniter 4.i had a problem is Record is not added in to the database. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!
We seem to have hit a snag. Please try again later... . i don't know how to solve problem what i tried so far i attached below.
View
User.php
<form method="post" id="add_create" name="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="empid" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<Button class="btn btn-success" style="width: 80px;">Submit</Button>
</div>
</form>
Controller
User.php
public function index()
{
return view('User');
}
// insert data
public function store() {
$userModel = new UserModel();
$data = [
'fname' => $this->request->getVar('fname'),
'lname' => $this->request->getVar('lname'),
];
$userModel->insert($data);
return $this->response->redirect(site_url('users'));
}
UserModel
<?php
namespace App\Models;
class UserModel extends Model
{
protected $table = 'records';
protected $primaryKey = 'id';
protected $allowedFields = ['fname', 'lname'];
}
Routes
$routes->get('/', 'User::index');
$routes->post('usersCreate', 'User::store');
I don't know CodeIgniter per se, but you should figure out how to get more meaningful data. Is your environment set to development environment? Usually you will get more info than Whoops! We seem to have hit a snag. Please try again later... and get more details on the error.
But I see you're trying to go to the page, where you add a user. There's 2 ways to methods to reach that page, GET (this is when you just go to the page as usual) and POST (this is when you submit the form).
But the request data will only be available if you submit the form. Thus you have to differentiate between the 2 methods. In your Controller you need to do something like
if ($this->request->getMethod() === 'post') { ... }
which is when you submit the form.
Check out https://codeigniter.com/user_guide/tutorial/create_news_items.html which should have more info. Snippet
public function create()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);
echo view('news/success');
}
else
{
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
I normally use a short method to get data and then submit it to the database. Here is what id do. check this. I am just updating your code
// insert data
public function store() {
$userModel = new \App\Models\UserModel();
$data = [
'fname' => $this->request->getPost('fname'),
'lname' => $this->request->getPost('lname'),
];
$userModel->insert($data);
return redirect()->to(site_url('users'));
}
then check you html file you are missing the firstname name
Try this one
<form method="post" id="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="fname" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<button type="submit" class="btn btn-success" style="width: 80px;">Submit</button>
</div>
</form>
For the check your model i think is not configured well check this one
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'object';
protected $useSoftDeletes = false;
protected $allowedFields = ['fname', 'lname', 'email']; // did you add this side of the site model
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
}
Check my code if it did not help you call my attentions okay. I am still ready to help
I'm a newbie in OctoberCms and i don't have much knowledge in Laravel also. While self studying I face a request like this it's a Select if record exist query I need to read the database and look for the match and I'm really confuse.
This is my form in form.htm where I design my Form.
use Drufal\DynamicContentManager\Models\MembersVerification;
==
<form data-request="onSend" accept-charset="UTF8" enctype="multipart/form-data">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" name="first_name" required>
</div>
<div class="form-group">
<label>Middle Name:</label>
<input type="text" class="form-control" name="middle_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" name="last_name" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
and this my model
<?php namespace Drufal\DynamicContentManager\Models;
use Model;
use Input;
/**
* Model
*/
class MembersVerification extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Disable timestamps by default.
* Remove this line if timestamps are defined in the database table.
*/
public $timestamps = false;
/**
* #var array Validation rules
*/
public $rules = [
];
/**
* #var string The database table used by the model.
*/
public $table = 'drufal_dynamiccontentmanager_members';
public function onSend(){
$fn = Input::get('first_name');
$mn = Input::get('middle_name');
$ln = Input::get('last_name');
$membertbl=$table::where('first_name', '=', $fn)->first();
if ($membertbl === null) {
echo"
<script>
alert('Successfully');
</script>
";
}else{
echo"NO RESULT";
}
}
}
Help the newbie please.
I think you missed the DB:: in your database request:
$users = Db::table('users')->where('votes', 100)->first();
Maybe this documentation will help you:
https://octobercms.com/docs/database/query#where-clauses
Im new in Laravel and i dont understand how to make action forms and routing for editing post
Here is my routes --
Route::post('/menu', 'MenuController#store');
Route::resource('/menu', 'MenuController');
here is controller --
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
return $id;
// $menus->name = $request->input('menuName');
//$menus->link = $request->input('menuLink');
//$menus->save();
//return redirect('/menu')->with('success', 'Menu updated');
}
Return $id is for check what "id" will give me and he gives me this- "{id}"
here is form --
<form action = "/menu/{id}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
i am really messed up allready and dont know what i am doing wrong. I cant understand why update funtion returns me "{id}" not value of ID and how can i make this all works
Your are not passing id in your view , you are passing it as a string , u need it create a variable and set it to the right id and pass it to your form.
Change your form action from
action = "/menu/{id}"
to
action = "/menu/".$id"
or you can use laravel blade
Form::open(['route' => ['menu.update', $id]])
and don't forget to close the form at the end
{!!Form::close!!}
You did something wrong with the action attribute. Change it to:
action="/menu/{{ $id }}"
Okay,
you have an edit method which will show the form, that method should return the menu object
public function update($id)
{
// get the menu you wan to edit
$menu = Menu::find($id);
// return the form with the menu object
return view('your.form.view', compact('menu'));
}
Now the form should be like this
// use that object u returned in the form action
<form action = "/menu/{{ $menu->id }}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
Now the update method should be something like this
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
// update the data
$bool = Menu::where('id',$id)->update([
'menuName'=> $request->menuName,
'menuLink'=> $request->menuLink,
]);
if(!$bool){
Session::flash('alert','error');
return view('page.index');
}
Session::flash('alert','success');
return view('page.index');
}
This first method is "get" edit that should show the form,
the second is put update that should receive the data from the form(after the show method) and use i to update.
I resolved the error ---
in update blade befor form i added foreach
<div class="container">
<div class="row">
#foreach($menus as $menus)
<form action="/menu/{{$menus->id}}" method="POST">
#endforeach
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
But now he is editing only 1st post and no matter wich post edit im switching
here is controller --
public function edit($id)
{
$menus = Menu::all();
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
menu list blade ---
#if(count($menus) > 1)
#foreach($menus as $menus)
<tr>
<th scope="row">1</th>
<td>{{$menus->name}}</td>
<td>{{$menus->link}}</td>
<td>{{$menus->created_at}}</td>
<td>{{$menus->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menus->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
Ok ive got it and resolved.
I will start with routes
routes----------
Route::resource('menu', 'MenuController');
that post route was unnecessary, but that didnt affect anything
controller -------
public function edit($id)
{
$menus = Menu::find($id);
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
Where in edit function i must find ID witch needs to be editing
menu list -----------------
#if(count($menus) > 1)
#foreach($menus as $menu)
<tr>
<th scope="row">1</th>
<td>{{$menu->name}}</td>
<td>{{$menu->link}}</td>
<td>{{$menu->created_at}}</td>
<td>{{$menu->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menu->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
<p class = "well"> No menu items created!</p>
#endif
I only changed $menus as $menus on "$menus as $menu" to be clear.
edit blade ------------
#extends('admin.main')
#section('content')
<div class="container">
<div class="row">
<form action="/menu/{{$menus->id}}" method="POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name" value="{{ $menus->name }}">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link " value="{{ $menus->link }}">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
#endsection
Here i deleted #foreach like #Snapey told and added the value option.
I guess value option gave me the errrors all the time.
Thank you all for attention and willing to help! Hope that someday i could help others with my knowledge.