I have a dropdownlist with 2 items (Carrot & Lemon). I want to compare Carrot to Lemon. If it is a vegetable the add is validated or else it is blocked in the form.
In my code, the validation is not correct... My 2 values pass...
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count();
$word = "Carrot";
if ($listVegetable == $word){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
With $listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count(); you get the amount of vegetables in your Database as Integer value. So your comparison with the carrot string does not make sense. You habe to write first() instead of count() and then I guess you need to access ->name property of this object, depending which rows your model has.
Ok, the main idea is verify if a string is into table, then you would take this way, just verify if string is into table:
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$vegetable = Exo::where('vegetables', $request->get('vegetables'))->first();
if ($vegetable){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
by other hand if you want to classify your Exo table, you'd need another colum, for example one called 'type', then the code looks like your main code(although it could be improved):
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$vegetable = Exo::where('vegetables', $request->get('vegetables'))->first();
$word = "vegetable";
if ($vegetable && $vegetable->type == $word){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
Hope this would help you.
Related
I want check if my form value equals in database value in laravel
Here is my controller class
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id , 'sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
What i do wrong?
update to
DB::table('users')->where(['id',$id ])->where([ 'sms_token_in'
,$sms_token])->update(['sms_verify'=>'1' ]);
The most simple way to use where is
two parameters, 1: database field name, 2: value
three parameters (field name, operator, value) ('1', '>=', 3)
DB::table('users')->where('id',$id)->where('sms_token_in', $sms_token)->update([
'sms_verify'=>'1'
]);
Try
DB::table('users')->where([
['id',$id],
['sms_token_in', $sms_token]
])->update([
'sms_verify'=>'1'
]);
First you must accept two parameter from your function. Look like only you are passing only one.
change function parameter to
public function code_post(Request $request, $id = 0)
then
if(!empty($id)){
User::where(['id' => $id,'sms_token_in' => $sms_token])->update([
'sms_verify'=>'1'
]);
}
// you can do this in two way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id)->where('sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
//2nd way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where(['id',$id , 'sms_token_in' ,$sms_token])->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
The best whey to do it is on Validators in laravel so, if it don't exist create a classe validator that extends "LaravelValidator" and do it:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'sms_token_in' => 'required|unique:your_table_name',
],
ValidatorInterface::RULE_UPDATE => [],
]; protected $messages = [
'sms_token_in.unique' => 'Your duplicate message!'
];
In your controller instantiate your validator in construct like it:
public function __construct(MyValidatorClass $validator)
{
$this->validator = $validator;
}
And in your controller function store do it, before your persist on database.
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
In this way, you can use validator from Laravel to check and return anything you want to your user.
function check(Request $request){
//validate
$request->validate([
'email'=>'required|email',
'user_pass'=>'required|min:5|max:12'
]);
$userInfo=Employee::where('email','=',$request->email)->first();
if(!$userInfo){
return back()->with('fail','We do not recognize your email address');
}else{
//check password
if($request->user_pass=$userInfo->user_pass){
$request->session()->put('LoggedUser', $userInfo->emp_id);
return redirect('/employee/dashboard');
}else{
return back()->with('fail','Incorrect password');
}
}
}
In this method im check if the user_pass from request is equal to $userInfo->user_pass that query from database.
if($request->user_pass=$userInfo->user_pass)
I have 2 tables, the first is Students with 3 fields (name, firstname, fk_diploma).Then, my second table is named Diplomas and there is 1 field named (type_diploma).
For information, I have 3 values in my field type_diploma:
1) DiplomaA
2) DiplomaB
3) DiplomaC
In my validate system, I want the DiplomaA or DiplomaB to be validated but not the DiplomaC, I must have an error message.
For example: * "Sorry, you do not have the skills for the diplomaC."
Do you have an idea of how I can do that ?
public function store(Request $request)
{
$diploma = Diploma::select('type_diploma')->where('id',$request->fk_diploma)->get();
if($diploma->type_diploma != 'DiplomaC')
{
$request->validate([
'name' => 'required|min:3',
'firstname' => 'required|min:2|max:200',
'fk_diploma' => 'required'
]);
}
$exists = Student::where('name', $request->get('name'))->where('firstname', $request->get('firstname'))->where('fk_diploma', $request->get('fk_diploma'))->count();
if (!$exists){
Student::create($request->all());
return redirect()->route('students.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('students.index')
->with('error', 'duplicate');
}
}
My model Diploma
class Diploma extends Model
{
protected $fillable = ['type_diploma'];
public function diplomas(){
return $this->hasMany('App\Student', 'fk_diploma');
}
}
Model Student
class Student extends Model
{
protected $fillable = ['name', 'firstname', 'fk_diploma'];
public function diplomas(){
return $this->belongsTo('App\Diploma' , 'fk_diploma');
}
This is not the best way to do it, but its the only one i could think right now:
1) change the type of your request to public function store(Request $request)
2) Do this in your function:
public function store(dateRequest $request)
{
$diploma = Diploma::select('type_diploma')->where('id',$request->fk_diploma)->get();
if($diploma->type_diploma != 'DiplomaA' && $diploma->type_diploma != 'DiplomaB')
{
$request->validate([
'name' => 'required|min:3',
'firstname' => 'required|min:2|max:200',
'fk_diploma' => 'required'
]);
}
$exists = Student::where('name', $request->get('name'))->where('firstname', $request->get('firstname'))->where('fk_diploma', $request->get('fk_diploma'))->count();
if (!$exists){
Student::create($request->all());
return redirect()->route('students.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('students.index')
->with('error', 'duplicate');
}
}
This will work for you:
$this->validate($request, [
'fk_diploma' => 'required|not_in:XXX',
]);
XXX - id of the diploma you don't want to accept
If you set relation ships between the User.php return $this->belongsTo('App\User'); and Profile.php return $this->hasOne('App\Profile', 'user_id', 'id'); how can u get a corresponding user to the profile when you only get the Profile variables. public function update(Request $request, Profile $profile)
i was thinking of something like this User::where(user->id==$profile->id); but its not working how would can you do it?
mine hole function:
if(\Auth::check()) {
if(\Auth::user()->type == 'admin'){
$validated = $request->validate([
'username' => 'required',
'email' => 'required|email',
'firstname' => 'required',
'lastname' => 'required',
'age' => 'required|numeric|max:150',
'birthdate' => 'required|numeric',
'bio' => 'required|min:30',
'select_file' => 'image|mimes:jpg,png,gif,jpeg|max:2048'
]);
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$profile->username = $validated['username'];
$profile->email = $validated['email'];
$profile->firstname = $validated['firstname'];
$profile->lastname = $validated['lastname'];
$profile->age = $validated['age'];
$profile->birthdate = $validated['birthdate'];
$profile->bio = $validated['bio'];
$profile->image_path = $new_name;
$profile->update();
$user = User::where(user->id==$profile->id);
$user->name = $validated['username'];
$user->email = $validated['email'];
$user->update();
return redirect()
->route('admin')
->with('succes', 'Profile updated succesfully');
} else {
return redirect()
->route('admin')
->with('fail', 'Profile is unable to be update successfully');
}
} else {
return redirect()
->route('login')
->with('fail', 'Profile is unable to be update successfully
because ur not an Admin');
}
Your where is not formatted properly. You need to pass in 2 (or 3) parameters, where the first is the column, and the second is the value you're checking for. If using 3 parameters, the second would be the operator (= or !=). Don't forget first() (for one record) or get() (for a collection of records), so that the query actually runs. Otherwise, it will just be the QueryBuilder object.
User::where('id', $profile->user_id)->first();
or
User::where('id','=', $profile->user_id)->first();
Since you're checking against the user's id, you can also use find() to get one record:
User::find($profile->user_id);
You can do it some ways.
Solution 1:
User::whereId($profile->user_id)->first();
Solution 2:
User::where('id', $profile->user_id)->first();
Solution 3:
User::where('id','=', $profile->user_id)->first();
Solution 4:
User::where(['id' => $profile->user_id])->first();
Also you can do it
In Profile model define
public function user()
{
return $this->belongsTo('App\User');
}
Than you can lazy load
$user = $profile->load('user')->user; // but it is lazy loading
I have 2 tables that are in one to one relationship:
tours :
id|title|content
featured_image:
id|tour_id|name|path
My models FeaturedImage.php:
class FeaturedImage extends Model
{
public function tour()
{
return $this->hasOne('App\Tour');
}
}
Tour.php
class Tour extends Model
{
public function featuredimage()
{
return $this->belongsTo('App\FeaturedImage');
}
}
I want to save tour_id in featured_image table when tour is created. I'm using same form to fill tours table and to upload featured_image.
This is my store method looks like:
public function store(Request $request)
{
//validate the date
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the date
$tour = new Tour;
$tour->title = $request->title;
$tour->content = $request->trip_code;
$tour->save();
$featured_image= new FeaturedImage;
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image->path= $location;
$featured_image->tour()->associate($tour);
$featured_image->save();
}
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
I'm successful to save data into tours table but unable to save in featured_image table. I 'm getting this error:
Call to undefined method Illuminate\Database\Query\Builder::associate()
I would be thankful if anyone can help me out.
You can user Mass Assignment to create your entries into DB like this:
$this->validate(request()->all(), [
'title' => 'required|max:255',
'content' => 'required'
]);
$tour_inputs = array_only(
$tour_inputs.
[
'title',
'content',
]
);
$tour = Tour::create($tour_inputs);
if($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featuredImage = $tour->featuredImage()->save(new FeaturedImage([
'name' => $filename,
'path' => $location,
]));
}
Remember to define the $fillables inside your models, your models should look like this,
do check your relations, that you've made in the models, according to me they aren't correct:
class Tour extends Model
{
protected $fillables = [
'title',
'content',
];
public function featuredImage()
{
return $this->hasOne('App\FeaturedImage');
}
}
class FeaturedImage extends Model
{
protected $fillables = [
'name',
'path',
'tour_id',
];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Hope this helps!
From your code the relationships that you have defined are in reverse order.
I mean logically, a Tour has one FeaturedImage and a FeaturedImage belongs to a Tour.
class Tour extends Model
{
//Mass Assignable fields for the model.
$fillable = ['title', 'content'];
public function featuredimage()
{
return $this->hasOne('App\FeaturedImage');
}
}
and
class FeaturedImage extends Model
{
//Mass Assignable fields for the model
$fillable = ['tour_id', 'name', 'path'];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Then in your controller
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
$tour = Tour::firstOrCreate([ //protection against duplicate entry
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
if($tour) //if the Tour exists then continue
{
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
//you could also have an else block to redirect back if the input doesn't have a file
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
else
{
//if there occurs any error display the error message and redirect back - probably with validation errors or exception errors
Session::flash('error','Error message');
return redirect()->back()->withInput()->withErrors();
}
}
And don't forget to add the mass assignable fields to the $fillable array on your models.
UPDATE
For cases where a single form submission includes database transactions in multiple tables, you should use a try{}catch{} to ensure that either all related transactions run without any issue or neither of the transactions go through - to avoid data discrepancy.
You can rewrite your controller code as
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
//use the DB::beginTransaction() to manually control the transaction
//You would ideally want to persist the data to the database only if the input provided by the user
//has valid inputs for Tour as well as FeaturedImage, in case if any one invalid input you do not
//want to persist the data
DB::beginTransaction();
try
{
//firstOrCreate gives protection against duplicate entry for tour with same title and content
$tour = Tour::firstOrCreate([
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
//proceed further only if $tour exists
if($tour)
{
// get featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
//save the featured_image
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
}
}
catch(\ValidationException $e)
{
//In case of validation error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Please check the provided inputs');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
catch(\Exception $e)
{
//In case of any other error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Something went wrong. Please try again');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
//If both the transactions to the database i.e. saving the Tour as well as FeaturedImage ran without problem
//Commit to the database
DB::commit();
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
Hope this helps.
I have been trying to update the handicap score using a post request. But I seem to get an error saying : creating default object from empty value.
Code :
public function handicap(Request $request)
{
$user = Auth::user();
$rules = array(
'handicap' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails())
{
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
else {
if(Handicap::where('user_id', '=', $user->id)->exists())
{
$handicap = Handicap::find($user->id);
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
else
{
$handicap = new Handicap;
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have added your handicap score successfully!'], 200);
}
}
}
If user does not exist in Handicap table then the else block code runs and creates a handicap score for the user else the if block needs to execute and update the score. I tried many alternatives but dont seem to get it working. Dont know what am I doing wrong.
I checked the $user, $handicap variables using return. those variables have the info that I need to add to the table. Its just that Its not updating.
Your problem probably comes from the line you have Handicap::find($user->id). Obviously it's null, because such model was not found, even though your if statement returns true.
In your if statement you have where('user_id' , '=', $user->id), but you are using Handicap::find($user->id) which is basically Handicap::where('id', '=', $user->id)->first().
Try changing it to:
$handicap = Handicap::where('users_id', '=', $user->id)->first();
You may give this a try:
public function handicap(Request $request)
{
$validator = Validator::make(Input::all(), [
'handicap' => 'required'
]);
// process the login
if ($validator->fails()) {
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
$handicap = Handicap::firstOrNew([
'user_id' => $request->user()->id;
]);
$handicap->user_id = $request->user()->id;
$handicap->handicap = $request->handicap;
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}