How to insert multiple rows in laravel 5? - laravel

I want to insert an array with an id :
create.blade :
{{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }}
<select id="disabledSelect" class="form-control" name="Facture_id">
<option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option>
</select>
<br/>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/>
</div>
<div class="form-group">
<input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" />
</div>
<div id="mydiv"></div>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-info">
Cancel
</div>
{{ Form::close() }}
<script>
var i = 2;
function createNew() {
$("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+
'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+
'<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+
'</div><br/>');
i++;
}
</script>
here is my controller , when I tried to submit the form , it inject rows with value of 0.
What should I do ? I tried to use elequent bolk data , but the problem remain the same:
public function store(Request $request)
{
// validated input request
$this->validate($request, [
'Facture_id' => 'required',
]);
// create new task
$rows = $request->input('rows');
foreach ($rows as $row)
{
$Charges[] = new Charge(array(
'course_id'=>$request->input('Facture_id'),
'Title'=>$row['Title'],
'Quantity'=>$row['Quantity'],
'Price'=>$row['Price'],
));
}
Charge::create($Charges);
return redirect()->route('Charge.index')->with('success', 'Your task added successfully!');
}

You can use insert() method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a $fillable array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];

Related

How To Update hasMany relationship data with multiple row at a time in Laravel?

I want to update SubCategory, which has a relationship with Category as a hasMany relationship. Now I want to update both category and subcategory at a time from one form. I want to update every subcategory which belongs to the category. But I can't do that.
Here is category model:
class Category extends Model
{
use HasFactory;
protected $guarded=[];
public function subcategory(){
return $this->hasMany('App\Models\SubCategory');
}
Here is subcategory model:
class SubCategory extends Model
{
use HasFactory;
protected $guarded=[];
public function category(){
return
$this>belongsTo('App\Models\Category','category_id','id');
}
here is update function in controller:
public function categoryUpdate(Request $request,$id){
if (is_null($this->user) || !$this->user->can('categories-update')) {
abort(403, 'Sorry !! You are Unauthorized !');
}
$request->validate([
'name' => 'required|max:191',
'status' => 'required',
]);
$Category=Category::findOrFail($id);
$Category->name = $request->name;
$Category->slug = Str::slug($request->name);
$Category->status = $request->status;
$Category->updated_by=Auth::user()->id;
$Category->update();
if($request->subcategory_name !=['']){
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
SubCategory::create([
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
]);
}
}
}
Alert::success('Success','Category has been updated successfully!');
return redirect()->route('category.index');
}
I don't know the code to update multiple subcategories at a time.
Here is the Html form
<form action="{{ route('category.update', $data->id) }}" method="POST">
#csrf
<div class="form-group">
<label for="" class="mb-2">Category name</label>
<input name="name" class="form-control" value="{{ $data->name }}" type="text"
#error('name') is-invalid #enderror" placeholder="Name">
#error('name')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div><br>
<div class="form-group">
<label for="" class="mb-2">SubCategory name</label>
#foreach ($subcat as $sub)
<div class="d-flex w-70 justify-content between mb-2">
<input name="subcategoryname[]" id="subcategoryname" class="form-control w-50" type="text" value="{{json_decode($sub->name)}}"></input>
<button onclick="deleteSubcategory({{$sub->id}})" id="delete_subcat" class="btn btn-danger btn-sm ms-2"><i
class="fa fa-trash text-dark" style="font-size:20px;color:white!important"
aria-hidden="true"></i></button>
</div>
#endforeach
</div><br>
<div class="form-group mt-2">
<label for="" class="mb-2">Add New SubCategory</label>
<div class="subcategory w-50">
<div class="d-flex mb-2">
<input name="subcategory_name[]" class="form-control" id="name" type="text"
placeholder="Name" multiple>
<span id="add" class="btn btn-dark ms-3">+</span>
</div>
</div>
<div class="form-group mt-2">
<label for="" class="mb-2">Status</label>
<br>
<select name="status" class="form-control" style="width:40%"
#error('status') is-invalid #enderror">
<option value="">--Select Status--</option>
<option value="Active" #if ($data->status == 'Active') selected #endif>Active
</option>
<option value="Inactive" #if ($data->status == 'Inactive') selected #endif>Inactive
</option>
</select>
#error('status')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div>
<div class="form-group mt-4 d-flex justify-content-between">
<button type="button" class="btn btn-secondary btn-sm"
data-bs-dismiss="modal">Cancel</button>
<input class="btn btn-primary btn-sm"type="submit" value="Update">
</div>
</form>
The create method takes array of records you want to save. So you can build an array and pass that array to the create method on the SubCategory.
if($request->subcategory_name !=['']){
$subCategories = [];
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
$subCategories[] = [
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
];
}
}
SubCategory::updateOrCreate(['name', 'slug'], $subCategories);
}

zoom integration MacsiDigital / laravel-zoom Call to a member function get() on null

i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
here is my code
this is my create blade
<form method="post" action="{{ route('online_classes.store') }}" autocomplete="off">
#csrf
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Grade_id">{{ trans('Students_trans.Grade') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="grade">
<option selected disabled>{{ trans('Parent_trans.Choose') }}...</option>
#foreach ($Grades as $Grade)
<option value="{{ $Grade->id }}">{{ $Grade->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="Classroom_id">{{ trans('Students_trans.classrooms') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="class">
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="section_id">{{ trans('Students_trans.section') }} : </label>
<select class="custom-select mr-sm-2" name="section_id">
</select>
</div>
</div>
</div><br>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>عنوان الحصة : <span class="text-danger">*</span></label>
<input class="form-control" name="topic" type="text">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>تاريخ ووقت الحصة : <span class="text-danger">*</span></label>
<input class="form-control" type="datetime-local" name="start_time">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>مدة الحصة بالدقائق : <span class="text-danger">*</span></label>
<input class="form-control" name="duration" type="text">
</div>
</div>
</div>
<button class="btn btn-success btn-sm nextBtn btn-lg pull-right"
type="submit">{{ trans('Students_trans.submit') }}</button>
</form>
and this is my fillable model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class online_class extends Model
{
protected $fillable = [
'grade_id',
'classroom_id',
'section_id',
'topic',
'start_at',
'duration',
'user_id',
'meeting_id',
'start_url',
'join_url',
'password',
];
public function user(){
return $this->belongsTo(User::class,'user_id');
}
}
and this is my store method in controller
public function store(Request $request)
{
$user = Zoom::user()->first();
$meeting = Zoom::meeting()->make([
'topic' => $request->topic,
'duration' => $request->duration,
'password' => $request->password,
'start_time' => $request->start_time,
'timezone' => 'Africa/Cairo',
]);
$meeting->settings()->make([
'join_before_host' => false,
'approval_type' => 1,
'registration_type' => 2,
'enforce_login' => false,
'waiting_room' => false,
]);
online_class::create([
'grade_id' => $request->grade,
'classroom_id' => $request->class,
'section_id' => $request->section_id,
'topic' => $request->topic,
'start_at' => $request->start_time,
'duration' => $meeting->duration,
'user_id' => Auth::user()->id,
'meeting_id' => $meeting->id,
'start_url' => $meeting->start_url,
'join_url' => $meeting->join_url,
'password' => $meeting->password,
]);
return $user->meetings()->save($meeting);
}

Laravel - How to update checkbox field value

Using Laravel-5.8, I have been able to save the data into the database including the check box field.
protected $fillable = [
'appraisal_name',
'is_current',
'appraisal_start',
'appraisal_end',
];
public function rules()
{
return [
'appraisal_name' => 'required|min:5|max:100',
'appraisal_start' => 'required',
'appraisal_end' => 'required|after_or_equal:appraisal_start',
'is_current' => 'nullable|boolean',
];
}
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
create.blade
<form action="{{route('appraisal.appraisal_identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
edit.blade
<form action="{{route('appraisal.appraisal_identities.update', ['id'=>$identity->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
I have these issues while trying to update the data?
The edit checkbox field (is_current) did not pick the value from the database when loaded. It remains unchecked.
is_current is either 0 or 1. The goal is that, there can only be one is_current field that is set to 1 in the table. From the checkbox, when is_current is checked to 1, it should set any other is_current that is 1 to 0 in the table.
How do I resolve these issues?
Thank you.
In edit blade update your checkbox code as this:
<input type="checkbox" class="form-control" name="is_current" #if($identity->is_current == 1) checked #endif value="{{old('is_current')}}">
In your update function change this:
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
In your store function change this:
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
try this in the edit blade
<
is_current == 1 ? checked : value="{{old('is_current')}}">

data isn't saving into db using eloquent relation

hi m trying to save data into db using Eloquent ORM one-to-one but it is not saving and not showing any error to fix it (m unable to find any solution about it because it is not showing any error),
public function store(Request $request)
{
$request->validate([
'owner_id' => 'required',
'phone_name' => 'required|unique:phones'
]);
$phone = new Phone;
$phone->owner_id = $request->owner_id;
$phone->phone_name = $request->phone_name;
$phone->save();
return redirect()->route('phone.index')->with('flash_messages_success', 'Phone has been added successfully');
}
protected $fillable = [
'pphone_name', 'owner_id'
];
public function owner()
{
return $this->belongsTo('App\Owner');
}
<form method="POST" action="{{ route('phone.store') }}">
#csrf
<div class="form-group">
<label for="">Phone Title</label>
<input type="text" name="phone_name" class="form-control" id="" placeholder="Phone Name">
</div>
<div class="form-group">
<label>Select Owner</label>
<select class="form-control" name="category_id">
<option selected="">Under Owner</option>
#foreach($owners as $owner)
<option value="{{ $owner->id }}">{{ $owner->owner_name }}</option>
#endforeach
</select>
</div>
<input type="submit" name="submit" class="btn btn-primary" value="submit">
</form>
The issue in select name you named category_id so the view should be:
<select class="form-control" name="owner_id">

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

Resources