Unkown column error for _method and _token in Laravel PUT form request. What is the cause? - sql

Column not found: 1054 Unknown column '_method' in 'field list'
Getting the above unknown column error for _method and _token but I have $fillable set in my model. What could be causing the error? I know the solution is Input::except('_method') in my controllers but I would like to understand the context of the issue.
Here is my code
protected $table = 'personaldetails';
protected $fillable = [
'address',
'city',
'country',
'postcode',
];
The relavant top part of my blade form...
<form action="{{ route('students.update', [$student->id]) }}" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" value="{{ Session::token() }}" name="_token">
<div class="row">
also tried with laravel { { csrf_field() } }.
public function update(Request $request, $id)
{
$inputData = $request->all();
$Student = Student::find($id);
$Student->personaldetail()->update($inputData);
return redirect()->route('Student.index')->with('message','Studenthas been updated'); }
Anyone else come across this too?

Per your comment response:
#JanWillem and tam I have added my controller that is bringing this
error up. I am unclear why it tries to store _method and _token. These
are not form values I want to store.
It's trying to store _method and _token because you're attempting to update the model w/ these attributes: $Student->personaldetail()->update($inputData);
As you've alluded to, you'll need to prune the list of attributes you'd like to update within the model from $inputData = $request->all(); to $inputData = $request->except('_method', '_token');

Related

Use of undefined constant message - assumed 'message' (this will throw an Error in a future version of PHP) laravel 6

Hi I was create one view and created one controller.
I want to give validation to form input field using bydeault Laravel error but I m getting error
"Use of undefined constant message - assumed 'message' (this will throw an Error in a future version of PHP)"
My code of controller and view as follow:
index.blade.php
#extends('app')
#section('title','Services Page')
#section('content')
<h1>Welcome to laravel 6 Services Section</h1>
<h4>lets do something better</h4>
<form action="/service" method="POST">
<input type="text" name="fname" autocomplete="off">
#csrf
<button>Add Service</button>
</form>
#error('fname') {{ message }} #enderror
<ul>
#forelse($services as $service)
<li>{{ $service->name }}</li>
#empty
<li>No services Available</li>
#endforelse
</ul>
#endsection
nd controller as follows :
ServiceController.php
public function store()
{
$name_validate = request()->validate([
'fname' => 'required'
]);
$service = new \App\Service();
$service->name = request('fname');
$service->save();
return redirect()->back();
// dd(request('fname'));
}
But I am getting error when form submit button not validate.
Any issue with this code let me know. I am new learner in laravel
Add the $ to the message:
#error('fname') {{ $message }} #enderror

using must in fluentValidation

I am using FluentValidation for the server side validation. Now I want to call a function using must.
This is the form code snippet :
<form method="post"
asp-controller="Category"
asp-action="SaveSpecification"
role="form"
data-ajax="true"
data-ajax-loading="#Progress"
data-ajax-success="Specification_JsMethod">
<input asp-for="Caption" class="form-control" />
<input type="hidden" asp-for="CategoryId" />
<button class="btn btn-primary" type="submit"></button>
</form>
What changes should I make to the code below to call function SpecificationMustBeUnique ?
public class SpecificationValidator : AbstractValidator<Specification>
{
public SpecificationValidator()
{
RuleFor(x => new { x.CategoryId, x.Caption}).Must(x => SpecificationMustBeUnique(x.CategoryId, x.Caption)).WithMessage("not unique");
}
private bool SpecificationMustBeUnique(int categoryId, string caption)
{
return true / false;
}
}
Tips: 1 - The combination of CategoyId and Caption should be unique
2 - Validation is not done when submitting the form(the validation just not running when submit the form)
The tricky part is deciding which property should be validated when the validation rule applies to a combination of values on different fields. I usually just close my eyes, and point to one of the view model properties and say "this is the property I'll attach the validator to." With very little thought. FluentValidation works best when the validation rules apply to a single property, so it knows which property will display the validation message.
So, just pick CategoryId or Caption and attach the validator to it:
RuleFor(x => x.CategoryId)
.Must(BeUniqueCategoryAndCaption)
.WithMessage("{PropertyName} and Caption must be unique.");
The signature for the BeUniqueCategoryAndCaption method would look like:
private bool BeUniqueCategoryAndCaption(Specification model, int categoryId)
{
return true / false;
}
Note: I guessed that the CategoryId property is an int, but you will need to make sure the categoryId argument to BeUniqueCategoryAndCaption is the same type as the CategoryId property in your view model.

passing data via redirect laravel 5

I have some problems when passing data via redirect in laravel 5, i get some samples code.. here my code
controller
if($validator->fails()){
return redirect()->back()->withErrors($validator->errors())->withInput();
}else{
if (Hash::check($request->old_password, $employee->password)){
$user = [
'username' => $input['username'],
'password' => Hash::make($input['password']),
];
$employee->fill($user)->save();
return redirect('/employees');
}else{
dd('test');
$error = 'Your old password is incorrect';
return redirect()->back()->with('error',$error);
}
}
view
<div class="form-group">
<label for="old_password" class="col-sm-2 control-label">Password Lama</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="old_password" placeholder="Password Lama" required />{{ $errors->first('old_password') }}{{ $error = session('error') }}
</div>
</div>
there is no error message, but $error cannot display my messages.. anyone can help me?
thanks a lot...
}else{
dd('test');
$error = 'Your old password is incorrect';
return redirect()->back()->with('error',$error);
}
with dd('test'), you are exiting the application before a value was stored in session. remove that and let redirect.
and secondly, while dealing with session, do not use dd(). it may create undesirable result as session is a terminable middleware.
The DD command returns info to the browser and then stops executing code. Try commented this out.

CodeIgniter Conditional - Multiple Tables

I'm stuck on the logic for a conditional that I need some help with. I am building a project collaboration platform where users can view open projects and join them to form a team. I've got the joining functionality working fine but I want to have a conditional set to not show the 'Join This Team' button if they are already a member of that project group. I may already have some of what is needed to do this but I'm not entirely sure how to go about it. (I had help writing the code I've already implemented) Here is the code below for joining a project:
//controller
public function join($project){
// Set Var
$email = $this->session->userdata('email');
// Join User
$this->project_model->join_project($project, $email);
//Redirect to Project
redirect('projects');
}
//functions in model to get the members already joined and insert
public function get_team_members($id){
$this->db->select('team_members.user_id, users.first_name, users.last_name, users.location');
$this->db->from('team_members');
$this->db->where('team_members.project_id', $id);
$this->db->join('users', 'users.id = team_members.user_id');
return $this->db->get()->result_array();
}
public function join_project($id, $email){
// Get UserID
$this->db->select('id');
$this->db->from('users');
$this->db->where('email', $email);
$user = $this->db->get()->row_array();
// Set Insert Data
$data = array(
'project_id' => $id,
'user_id' => $user['id']
);
// Insert into Team DB
$this->db->insert('team_members', $data);
}
//view
<div class="large-4 columns widget">
<div class="row collapse top-margin">
<div class="large-4 columns"></div>
<div class="large-8 column bottom-spacer">
<?php $link = base_url()."project/join/".$project['project_id']; ?>
<h5>Join this Team</h5>
</div>
</div>
//view for team members
foreach ($team as $member){ ?>
<!-- Team Member #1 -->
<div class="row collapse">
<div class="large-4 columns">
<img class="left" src="<?php echo base_url();?>assets/img/user.png" alt="user img">
</div>
<div class="large-8 columns member-name">
<p class="name"><strong><?php echo $member['first_name']." ".$member['last_name']; ?></strong></p>
<p><span><?php echo $member['location'];?></span></p>
</div>
</div>
<?php } ?>
Any help would be greatly appreciated.
You can do with two method.
Method 1. Create function is_team_member($user_email, $team_id) in your model. If user exist, true will be return else false. Pass the returned value to view via controller. Based on the value you can hide the button with use of if condition.
Method 2. You can check the user email in view foreach loop. If $email == $member["email"], set flag to hide button. But in this case, your button should be under the member list. Bur, as we discussed in comment, your member list is above list. So create a variable to store the foreach html content as string. you can run the foreach loop above the button and cho the content after the button. Now based on the flag, you can hide the button.
Ex for method - 1:
In Controller, Team member listing function.
public function index($team_id){
// Set Var
$email = $this->session->userdata('email');
$data["team"] = $this->project_model->get_team_members($team_id);
$data["is_joined_user"] = $this->project_model->is_team_members($team_id,$email);
//load view
$this->view->load("view_name", $data);
}
In model:
public function is_team_members($team_id,$email)
{
$this->db->select('*');
$this->db->from('team');
$this->db->join('users', 'users.id = team.user_id');
$this->db->where("user.email",$email);
$res = $this->db->get();
if($res->num_rows()>0)
return true;
else
return false;
}
In view:
<?php
if(! $is_joined_user)
{
?>
<h5>Join this Team</h5>
<?php
}
?>

Orchard Module - How to return strongly typed Model rathen than dynamic from Driver

I created a ContactUs module that sends email when user click on Submit button.
Everything works perfectly. However, I am curious if it is possible to return a strongly typed Model rather than dynamic class.
For example, following is my Drivers\ContactUsDriver.cs Display function:
protected override DriverResult Display(ContactUsPart part, string displayType, dynamic shapeHelper)
{
return ContentShape("Parts_ContactUs",
() => shapeHelper.Parts_ContactUs(
Name: part.Name));
}
As you can see, above is returning a dynamic Parts_ContactUs.
Now, here's snapshot of my Views\Parts\ContactUs.cshtml:
#model dynamic
#using (Html.BeginForm("Send", "ContactUs", new { area = "ContactUs" }, FormMethod.Post))
{
<fieldset>
<legend>Contact Us</legend>
<div id="contact-us" class="area">
#Html.TextBox("Name", "")
</div>
<div id="submitArea" class="button">
<input type="submit" value="Submit Message">
</div>
</fieldset>
}
As you can see above the View is bound to #model dynamic. As a result, I have to do following
#Html.TextBox("Name", "")
Is there a way I can bind to Model say ContactUsModel and thus do following instead?
#Html.TextBoxFor(m => m.Name)
Particularly, I am interested so I can write a jquery validation with DataAnnotation attribute.
It's perfectly possible. Just provide a desired model type as your first argument when creating a shape:
protected override DriverResult Display(
ContactUsPart part,
string displayType,
dynamic shapeHelper)
{
return ContentShape("Parts_ContactUs",
() => shapeHelper.Parts_ContactUs(typeof(MyClass), Name: part.Name));
}