foreach error laravel multiple checkbox store - laravel

I store a few checkboxes as array in Laravel, but I get an error on Foreach. Can someone help me?
in model
public function setHandServiceAttribute($value)
{
$this->attributes['handservice'] = json_encode($value);
}
public function getHandServiceAttribute($value)
{
return $this->attributes['handservice'] = json_decode($value);
}
in checkbox
<div class="form-check mx-3">
<input class="form-check-input" type="radio" id="1" value="کاشت" name="handservice[]">
<label class="form-check-label" for="1">کاشت</label>
</div>
<div class="form-check mx-3">
<input class="form-check-input" type="radio" id="2" value="کاور" name="handservice[]">
<label class="form-check-label" for="2">کاور</label>
</div>
handservice is column of reservation table in database with value like this after store
["\u062a\u0631"]
and in view
#forelse($reservation->handservice as $hand)
{{ $hand }},
#empty
nothing
#endforlse
error
json_decode(): Argument #1 ($json) must be of type string, array given
I used this article but I get an error when one of the columns handservie is empty handservice in nullable
https://hackthestuff.com/article/how-to-store-multiple-checkbox-value-in-database-in-laravel8

It finally worked
in model
public function getHandServiceAttribute($value) {
return json_decode($value);
}
in view
#if($reservation->handservice != null)
#forelse($reservation->handservice as $hand)
{{$hand}},
#empty
نا مشخص
#endforelse
#else
<p class="text-danger">انتخاب نشده</p>
#endif
thanks all

You shouldn't try to assign something in a getter.
public function getHandServiceAttribute()
{
return json_decode($this->attributes['handservice']);
}

Related

Undefined variable $attendance_status using radio button laravel

i am using laravel query builder but the problem is i am using radio buttons but i want to update the attendance at the radio button but it returns an error Undefined variable $attendance_status
i don't know why please help and how can i pass the $attendance_status variable
here is my code
my form
<form action="{{route('Attendances.update',$student->id)}}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$student->id}}">
<label class="block text-gray-500 font-semibold sm:border-r sm:pr-4">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 1 ? 'checked' : '' }}
class="leading-tight" type="radio" value="presence">
<span class="text-success">حضور</span>
</label>
<label class="ml-4 block text-gray-500 font-semibold">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }}
class="leading-tight" type="radio" value="absent">
<span class="text-danger">غياب</span>
</label>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">{{trans('Students_trans.Close')}}</button>
<button class="btn btn-danger">{{trans('Students_trans.submit')}}</button>
</div>
</form>
here is my controller
update
public function update(Request $request, $id)
{
// return $request;
if($request->attendances == 'absent'){
$attendance_status = 0;
}
else if($request->attendances == 'presence'){
$attendance_status = 1;
}
Attendance::find($id)->update([
'student_id'=> $id,
'grade_id'=> $request->grade_id,
'class_id'=> $request->classroom_id,
'section_id'=> $request->section_id,
'attendance_date'=> date('Y-m-d'),
'status' => $attendance_status,
]);
return back();
You have an if and an elseif in your Controller, so only 2 conditions would create a variable named $attendance_status. You probably want to add a default branch, else basically, to make sure that the variable gets created with some default value before you try to use it in your update call.
Not sure which one of those 2 options you want to be the default but this would simplify things:
$attendance_status = $request->attendences == 'presence';
https://laravel.com/docs/9.x/redirects#redirecting-with-flashed-session-data
You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. Once the input has been flashed to the session, you may easily retrieve it during the next request:
return back()->withInput();
Surely {{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }} logic does not work in this way.
try this instead
<input name="attendences" checked="{{ $student->attendances()->first()->attendence_status == 0 ? true : false}}" class="leading-tight" type="radio" value="absent">

I am trying to add rating to a user and running in to error Call to a member function Review() on null. in laravel 5.8

i am trying to add rating and reviews to the user here is so far what i have done
i have made a separate controller for review
and in the store method of that controller my code is as follow
public function store(Request $request,User $user)
{
//
$up=User::find($user->id);
if($request->review)
{
$up->Review()->attach($request->review);
}
if($request->rating)
{
$up->Review()->attach($request->rating);
}
return redirect()->back();
}
i have created a seprate model for the review as well in which my code is looks like this
class Review extends Model
{
//
protected $fillable=['rating','review'];
Public function User()
{
return $this->belongsToMany(User::class);
}
}
where in my user model i have made this
Public function Review()
{
return $this->belongsToMany(Review::class);
}
where as my migrations looks like this
public function up()
{
Schema::create('review_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('rating');
$table->string('review');
$table->timestamps();
});
}
my forms looks like this
<form action="{{route('ReviewsUser',$user->id)}}" method="POST">
#csrf
#method('PUT')
<div class="feedback-yes-no">
<strong>Your Rating</strong>
<div class="leave-rating">
<input type="radio" name="rating" id="rating-1" value="1" checked/>
<label for="rating-1" class="icon-material-outline-star"></label>
<input type="radio" name="rating" id="rating-2" value="2"/>
<label for="rating-2" class="icon-material-outline-star"></label>
<input type="radio" name="rating" id="rating-3" value="3"/>
<label for="rating-3" class="icon-material-outline-star"></label>
<input type="radio" name="rating" id="rating-4" value="4"/>
<label for="rating-4" class="icon-material-outline-star"></label>
<input type="radio" name="rating" id="rating-5" value="5"/>
<label for="rating-5" class="icon-material-outline-star"></label>
</div><div class="clearfix"></div>
</div>
<textarea class="with-border" placeholder="Enter Your Comments" name="review" id="review" cols="7" required></textarea>
<!-- Button -->
<button class="button full-width button-sliding-icon ripple-effect" type="submit" >Your Review's <i class="icon-material-outline-arrow-right-alt"></i></button>
</form>
what i am trying to do is to store reviews that other users have given the user anyone who can help me overcome this error would be highly appreciated .
Call to a member function Review() on null
This error means that your variable $up calling the member function Review() has a null value. Which means it's not finding your user in
$up = User::find($user->id);
Your post route doesn't have a route parameter to pass the user ID to find the user in the first place.
Therefore, changing this
Route::post('Reviews','ReviewsController#store')->name('ReviewsUser');
to this
Route::post('Reviews/{user}','ReviewsController#store')->name('ReviewsUser');
will now capture the User ID in your controller via User $user

Issue with passing values from Form and Controller to Blade in Laravel

I have issue with send values from address localhost/product/1/1 to my database, I want attach product 1 to customer 1 and add special prices below I add code
Route:
Route::get('/product/{customerID}/{productID}', 'CustomerController#insertCustomerProductForm')->name('add-product');
Route::post('/product/{customerID}/{productID}', 'CustomerController#insertCustomerProductAction');
to Controller
insertCustomerProductForm method:
public function insertCustomerProductForm($customerID, $productID)
{
return view('customer_products.create', [
'customer' => Customer::find('$customerID'),
'product' => Product::find('$productID'), ]); }
insetCustomerProductAction method:
public function insertCustomerProductAction (Request $request, $customerID, $productID) {
$newCustomerProduct = new CustomerProduct;
$newCustomerProduct->product_id = $productID;
$newCustomerProduct->customer_id = $customerID;
$newCustomerProduct->selling_customer_price = $request->input('selling_customer_price');
$newCustomerProduct->purchase_customer_price = $request->input('purchase_customer_price');
$newCustomerProduct->consumed_customer_price = $request->input('consumed_customer_price');
$newCustomerProduct->save(); }
Model CustomerProduct
class CustomerProduct extends Model
{
public function customers()
{
return $this->belongsToMany(Customer::class);
}
public function products()
{
return $this->belongsToMany(Product::class);
}}
and when I try use in blade set values for product of customer I have only from form values (selling_customer_price... etc) nothing about product and customer? I don't know why or this find method is problem? Because I have to store special price for special customer in this form.
below I add part of blade code
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dodaj Produkt') }} </div>
<div class="card-body">
<form method="post">
#csrf
<div class="form-group row">
{{ $customer }}
<label for="selling_customer_price " class="col-md-4 col-form-label text-md-right">{{ __('Cena Sprzedaży') }}</label>
<div class="col-md-6">
<input id="selling_customer_price " type="text" class="form-control{{ $errors->has('selling_customer_price ') ? ' is-invalid' : '' }}" name="selling_customer_price " value="" required autofocus>
#if ($errors->has('selling_customer_price '))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('selling_customer_price ') }}</strong>
</span>
#endif
</div>
my error looking like it don't see variables from form:
selling_customer_price, purchase_customer_price, consumed_customer_price
I have error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'selling_customer_price' cannot be null (SQL: insert into `customer_products` (`product_id`, `customer_id`, `selling_customer_price`, `purchase_customer_price`, `consumed_customer_price`, `updated_at`, `created_at`) values (1, 1, , , , 2018-07-09 12:39:03, 2018-07-09 12:39:03))
Where exactly is your error coming from in both cases? insertCustomerProductForm should be working fine, as long as you pass the right parameters in the URL like so: localhost/product/20/10
POST request generally don't need parameters in the URL itself. You can retrieve the POST variables by doing $_POST['selling_customer_price'] in your insertCustomerProductAction method.

How to return view in controller?

I need to pull in data to my view but this doesn't work:
return view ('sub-domain', ['worker' => $worker ]);
Here is my code:
public function aerospace(Request $request , Worker $worker ){
$worker = $worker->newQuery();
if ($request->has('profession')) {
$worker->where('profession', $request->input('profession'));
}
if ($request->has('state')) {
$worker->where('state', $request->input('state'));
}
if ($request->has('local_govt')) {
$worker->where('local_govt', $request->input('local_govt'));
}
return $worker->get();
The above code brings out an array of data from the database which I can then filter with "domain/sub-domain?state=xyz"
Now when I try to pass in the data into my views using
return view ('sub-domain', ['worker' => $worker ]);
The page is loaded but no $worker data is loaded on the page. How can I pull the data? Here is my view file
<div class="row">
<form method="GET" action="">
Profession:<input type="text" name="profession"> State:<input type="text" name="state"> Local Govt:<input type="text" name="local_govt">
<button type="submit">Filter</button>
</form>
</div>
<div class="row">
#foreach ($worker as $worker)
<div class="col-lg-3 col-md-6">
<div class="member">
<div class="pic"><img src="avatar/{{$worker->avatar}}" alt=""></div>
<div class="details">
<h4>{{$worker->name}} {{$worker->l_name}}</h4>
<span>{{$worker->profession}}</span><br>{{ $worker->state }}
</div>
</div>
</div> #endforeach
</div>
I want to filter data by certain parameters, if there's a better way to do that please do let me know. But first I need the data to display.
You are returning a query instance, not a collection or singular model. That's why the get() method works. So first do:
$worker = $worker->get();

Laravel applying search filers

I have a page which has a search box(input text) which takes a place name as input and returns all the nearby dealers.
I also happen to have filters (checkboxes) for all the brand
<div class="col-sm-12 col-md-12">
{!! Form::checkbox('filters',$bike_oem, false,['style'=>'padding-right:5px;'] ) !!} <span style="padding-left:5px;"></span>{{ $bike_oem }}
</div>
How do I implement get the value of filter in my controller ?
<div class="col-sm-12 col-md-12">
<input style="padding-right:5px;" name="Hyundai " type="checkbox" value="Y"> <span style="padding-left:5px;"></span>Hyundai
</div>
This is how each filter appears in the page. Is the code correct to fetch the value in controller ? Please suggest
You can get the value of checkbox in this way also(in controller)
public function myFunction(Request $request){
if (isset($request['Hyundai']) && ($request['Hyundai'] == "on")) {
$value = "Y";
}
}

Resources