How to solved Invalid argument supplied for foreach() - laravel

I am tired to solve the problem. I will see that everything is ok. but maybe there is any wrong. why that showing Invalid argument supplied for foreach(). What is wrong here? Please solved it.
<form action="{{route('send.email.noactiveusers')}}" method="post">
#csrf
<div class="form-group row">
<label class="col-form-label col-lg-2">To All No Active users</label>
<div class="col-lg-10">
<select multiple="multiple" class="form-control select" name="noactivemail" data-fouc>
<optgroup label="Subscribed users">
#foreach($client as $val)
#if($val->NoActivities($val->last_deposit)==="yes")
<option value="{{$val->email}}" selected>{{$val->email}}</option>
#else
#endif
#endforeach
</optgroup>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-lg-2">Subject:</label>
<div class="col-lg-10">
<input type="text" name="subject" maxlength="200" value="No activities for over 3 months"
class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-lg-2">Message:</label>
<div class="col-lg-10">
<textarea type="text" name="message" rows="4" class="form-control tinymce">We see that no activities over 3 months on your account. If you want to stay active in your account then please deposit on your account within 7 days. Otherwise, your account deactivated.</textarea>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn bg-dark">Send<i class="icon-paperplane ml-2"></i></button>
</div>
</form>
public function SendEmailtoNoActiveUsers(Request $request)
{
$set=Settings::first();
foreach ($request->noactivemail as $email) {
$user=User::whereEmail($email)->first();
send_email($user->email, $user->name, $request->subject, $request->message);
}
return back()->with('success', 'Message sent!.');
}

you are using multiple select but you are not using an array to send those selected values. when you are sending multiple values with the same name attribute you have to make it an array. so just update your select with
<select multiple="multiple" class="form-control select" name="noactivemail[]" data-foucs>
this will send an array named noactivemail with your form request. and you can then iterate in the controller.
foreach ($request->noactivemail as $email) {
$user = User::where('email', $email)->first();
send_email($user->email, $user->name, $request->subject, $request->message);
}

Related

Cannot find errors returned by validate method

I am using the validate method to validate user input and when I post a form with errors, I get redirected to the previous page but the form is not repopulated and the errors are not showing. I have include a partial view for showing errors in the page with the form. The partial view is:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
the action method in the controller is:
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'age' => 'required',
'product_code' => 'required|alpha_num',
'price' => 'required|numeric',
]);
$product=new Product();
The view with the form is:
#section('content')
<div class="container">
#include('partials.errors')
<form action="/products/create" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
#csrf
<div class="form-group">
<label>Product Name</label>
<input name="product_name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Age</label>
<input name="age" type="text" class="form-control">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control" name="gender">
<option>
Male
</option>
<option>
Female
</option>
Unisex
</option>
</select>
</div>
<div class="form-group">
<label>Product Code</label>
<input name="product_code" type="text" class="form-control">
</div>
<div class="form-group">
<label>Price</label>
<input name="price" type="text" class="form-control">
</div>
<div class="form-group">
<label>Product Category</label>
<select class="form-control" name="category_name">
#foreach ($product_categories as $product_category)
<option>{{ $product_category->category_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" name="brand_name">
#foreach ($brands as $brand)
<option>{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
</div>
#endsection
when I post a failed form, I get redirected to the view with the form but the form is not repopulated with the input that I entered. additionally, the erros are not shown but just an empty red div. According to a book I read, if the data isn’t valid, the validate method throws a ValidationException and the exception will return a redirect to the previous page, together with all of the user input and the validation errors. I am new to laravel.
You should use old() method to keep repopulate entered value in input field like below
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
To show validation error you have to add errors in each field for example like below
#error("product_code")
<div class="invalid-feedback">{{ $message }}</div>
#enderror
You can read more about old method here
https://laravel.com/docs/8.x/requests#retrieving-old-input
For validation error
https://laravel.com/docs/8.x/validation#the-at-error-directive
First, the CSRF token:
If you check the docs you'll see that you have 2 options how to add it:
#csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
You are doing both, remove one of them.
Second, the old input:
You are missing the old input call. For example:
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
Last, the errors:
You are doing it correctly.
If is still not working, check that your route is using the middleware web.

checked for multiple checkbox in update form

This is my blade file for the update form. So how I should I retrieve those data in the form by checked the checkbox.
<div class="form-group row">
<label class="col-md-3 col-form-label form-control-label" for="input-description">Hobbies</label>
<div class="col-md-9">
<input type="checkbox" name="hobbies[]" class="form-control-label" value="football" > Football
<input type="checkbox" name="hobbies[]" class="form-control-label" value="basketball"> Basketball
<input type="checkbox" name="hobbies[]" class="form-control-label" value="table_tennis"> Table Tennis
<input type="checkbox" name="hobbies[]" class="form-control-label" value="hockey"> Hockey
<input type="checkbox" name="hobbies[]" class="form-control-label" value="others"> Others
</div>
</div>
</div>
This is my Controller
public function edit($id)
{
$student=Student::find($id);
return view('students.edit', compact('student'));
}
In the database, .hobbies are stored in hobbies column like this
["basketball","football",'table_tennis']
You should use foreach loop inside blade that will be more maintainable:
<div class="form-group row">
<label class="col-md-3 col-form-label form-control-label" for="input-description">Hobbies</label>
<div class="col-md-9">
#foreach($hobbies as $hobby)
<input type="checkbox" name="hobbies[]" #if(in_array($hobby,$checked_hobbies)) checked #endif class="form-control-label" value="{{ $hobby }}" > {{ $hobby }}
#endforeach
</div>
</div>
and of course you should pass hobbies and checked_hobbies array in controller:
$hobbies = ["basketball","football",'table_tennis'];
$checked_hobbies = ["basketball","football"];
return view('test', compact('hobbies','checked_hobbies'));

Update single field in a Profile Update Form in Laravel 5

I am trying to update a single field in my user profile form section in the Laravel app.
I can save fields correctly in DB but input values and placeholders are taking wrong values. In every hit Save, the values doesn' change, and they are taken from the last listed user profile details. In my case this is user#3. The problem is when I log in with the user's #1 credentials, value and placeholder are taken from user #3. When I log in with user #2, again from user #3. Only values of user#3 are correct and I can manipulate it with no issues for both fields.
When i update the profile fields with user#1 it saves the entered one filed, but because the 2nd filed inherits the user#3 input details it saves it in field 2 of user#1 which makes a wrong entry. I can't leave null in those fields by default. My mass assignment is guarded.
How can save/update just a single field in the blade template without affecting the other fields in the form?
My routes:
Route::get( '/profile', 'userController\\profileEdit#profileEdit')->name('profileEdit');
Route::post('/profile', 'userController\\profileEdit#update')->name('update');
My controller:
namespace App\Http\Controllers\userController;
use App\Model\Hause_users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class profileEdit extends Controller
{
function profileEdit (Request $request){
$user = Hause_users::all();
$name = $request->session()->get('name');
$request->session()->keep([request('username', 'email')]);
return view('frontview.layouts.profile',['user'=>$user])->with('username' , $name );
}
function update (Request $request){
$user = Hause_users::where('username', $request->session()->get('name'))->first();
$user->fill(['email' => request('Email')]) ;
$user->save();
$user->phone;
//dd($user->phone->phone);
if ($user->phone === null) {
$user->phone->phone->create(['phone' => request('tel')]);
}
else{
$user->phone->update(['phone' => request('tel')]);
}
return back()->withInput();
}
Blade file: `
#extends('frontview.layouts.userView')
#extends('frontview.layouts.default')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#section('title')
#endsection
#section('content')
#foreach($user as $v )
#endforeach
<h2 class="form-group col-md-6">Здравей, {{$username }} </h2>
<form class = "pb2" method="POST" name = 'profile' action='profile' >
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="email" class="form-control" name = "Email" id="inputEmail4"
value="{{$v['Email']}}"
placeholder="{{$v->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$v->phone['phone']}}"
placeholder="{{$v->phone['phone']}}"
id="example-tel-input" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity">Град</label><input type="text" class="form-control" id="inputCity">
<label for="inputCity">Квартал</label><input type="text" class="form-control" id="inputCity">
</div>
{{--<div class="col-md-6" >--}}
{{--<label for="image">Качи снимка</label>--}}
{{--<input type="file" name = "image">--}}
{{--<div>{{$errors->first('image') }}</div>--}}
{{--</div>--}}
</div>
{{--<div ><img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg"--}}
{{--class="rounded-circle z-depth-1-half avatar-pic" alt="example placeholder avatar">--}}
{{--</div>--}}
{{--<div class="d-flex justify-content-center">--}}
{{--<div class="btn btn-mdb-color btn-rounded float-left">--}}
{{--<span>Add photo</span>--}}
{{--<input type="file">--}}
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Запомни ме!
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Запази</button>
</form>
#endsection
#section('name')
{{ $username }}
#endsection
Output summary:
On img#1 are the correct entry details . This is other section not the Profile edit one. Currently loged user is U#1 but as you can see on image 2, values and placeholder of both fields are for the U#3. When i hit the blue button U#1 saves the untouched filed input of U#3. Same is when i log in with U#2.
Actually the answer here is quite simple. What i am doing wrong is that i am not passing the value of the currently logged user to the view correctly. On my profileEdit method i was using $user = Hause_users::all(); and then looping trough all id's into the view and then fetching every field. But because the view doesn know which user passes the data, the foreach always returns the last user id from the array with its input, no matter which user is currently logged in. Then the data was overridden with wrong inputs.
The solution is also simple.
Instead of $user = Hause_users::all();
i have used
$user = Hause_users::where('username', $request->session()->get('name'))->first();
and then into view i was objecting the $user variable without any loops like this:
<form class = "pb2" method="POST" name = 'profile' action='profile' >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{{--<input type="hidden" name="_method" value="PATCH">--}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="Email" class="form-control" name = "Email" id="inputEmail4"
value="{{$user->Email}}"
placeholder="{{$user->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$user->phone['phone']}}"
placeholder="{{$user->phone['phone']}}"
id="example-tel-input" >
Basically this is a detailed explanation to all that not using the built in Auth system of Laravel

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

cannot show data from model object

I want to change the data absent but an error appears 'Trying to get the property' id 'of non-object' I do not understand why even though I have done it before and it's fine. and my relationship table is in apache MySql so my model is blank.
I've tried to match my other edit method but nothing is wrong
this my edit()
public function edit($id)
{
$absensi = absensi::find($id);
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
return view('absensi.edit', ['absensi'=> $dataSiswa]);
}
and then this is my blade
<div class="card-header">
<h1>Edit Data Absensi </h1>
</div>
<div class="card-body">
<form action="/absensi/{{$absensi->id}}" method="POST" name="form1" >
{{ csrf_field() }}
<div class="form-group">
<label for="usr">Nama :</label>
<input type="text" value="{{$dataSiswa->nama}}">
</div>
<div class="form-group">
<label for="usr">Semester :</label>
<select name="semester" class="form-control" id="sel1">
<option value="genap"#if ($dataSiswa->semester=="ganjil") selected #endif>ganjil</option>
<option value="ganjil"#if ($dataSiswa->semester=="genap") selected #endif>genap</option>
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" name="kelas" value="{{$dataSiswa->kelas}}">
</div>
<div class="form-group">
<label for="comment">izin:</label>
<input type="number" class="form-control" name="izin" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Sakit :</label>
<input type="number" class="form-control" name="sakit" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Tanpa Keterangan :</label>
<input type="number" class="form-control" name="tanpaKeterangan" value="{{$dataSiswa->izin}}">
</div>
<button type="submit" class="btn btn-primary" id="Submit" name="Submit">simpan perubahan</button>
</form>
</div>
</div>
</div>
change
$absensi = absensi::find($id);
to
$absensi = absensi::findOrFail($id);
i think the problem is that the model cannot find the record with that id
and if thats not the case then
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
to
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
if(!$dataSiswa) {
// throw new notfound exception here or return back
}
return view('absensi.edit', ['absensi'=> $dataSiswa]);
In other words you are trying to access a property of a null object because the queries you made are returning a null object, and on your blade you are tying to access a null object property
You should probably look into defining your relationships with eloquent instead as per the docs.
Once that's done you can use Eloquent to query your table like so:
$abensis = abensis::findOrFail($id);
$dataSiswa = $abensis->siswa;
return view('absensi.edit', ['absensi'=> $dataSiswa]);

Resources