Problem passing data from the controller to the view Laravel 8 - php

I'm getting an error when I try to pass data from the controller to the view and I spent a lot of time trying to solve it. The error is "Undefined Variable $instEntNacs". There is other form this view, because depending on the rol, it will show the first or the second one.
Here's the controller "ConvenioController":
public function create()
{
$instEntNacs = DB::table('inst_ent_nacs')->select('id', 'nombre')->get();
return view('convenios.create', ['instEntNacs' => $instEntNacs]);
}
And the view:
#if (auth()->user()->rol_id == "2")
<form method="POST" class="form-conv-nac border border-2 rounded-3 shadow-lg" action="{{ route('convenios.store_nac') }}" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="offset-1 col-10 mt-4">
<select class="form-control border border-dark" id="con_instEntNac" name="con_instEntNac">
<option selected value="">-- Institución o Entidad --</option>
#foreach ($instEntNacs as $item)
<option value="{{ $item->id }}"> {{ $item->nombre }}</option>
#endforeach
</select>
</div>
</div>
<div class="row mt-4 mb-5">
<div class="offset-1 col-2">
Regresar
</div>
<div class="offset-2 col-3">
<button type="submit" class="w-100 btn_2 btn-danger rounded-pill border border-dark">Cancelar</button>
</div>
<div class="col-3">
<button type="submit" class="w-100 btn_1 btn-primary rounded-pill border border-dark">Registrar</button>
</div>
</div>
</form>
#endif

Have you tried this?
$data['instEntNacs'] = DB::table('inst_ent_nacs')->select('id', 'nombre')->get();
return view('convenios.create')->with($data);

You can try compact('instEntNacs') with return view('convenios.create').
return view('convenios.create', compact('istEntNacs'));

Related

Laravel form validation doesn't work when in my controller declaring more databases

I declare a variable containing the database so that the blade can select, but when doing so, the validation does not work. Please help me. Thank you very much.
this is the variable I call in the database to use select in the blade.
public function new_department(){
//return view('admin.new-department');
$manage_faculties=DB::table('faculties')->orderBy('id','asc')->get();
$all_manage_faculties=view('admin.new-department')->with('manage_faculties', $manage_faculties);
return view('layouts.master')->with('admin.new-department', $all_manage_faculties);
}
Here is the validation I use in the insert information and database.
public function save_new_department(Request $request){
$data = [];
$data['department_name'] = $request->input('department_name');
$data['description'] = $request->input('description');
$data['faculty_id'] = $request->input('faculty_name');
if($request->isMethod('post')){
$validator = Validator::make($request->all(), [
'department_name' => 'required|min:3|max:100|unique:departments',
'description' => 'required|max:500',
]);
if ($validator->fails()) {
return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
}
DB::table('departments')->insert($data);
return redirect('/admin/departments/new')->withSuccess('Post Created Successfully!');
}
}
display it in the blade
After entering data whether it is true or false, it is not possible to report an error on the screen.After entering data whether it is true or false, it is not possible to report an error on the screen.
<form class="mt-3"method="post" action="{{ url('admin/department/new-department') }}">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title">Create a Department</h5>
</div>
<!--end of modal head-->
<div class="modal-body">
<div class="form-group row align-items-center" {{ $errors->get('name') ? 'has-error' : '' }}>
<label class="col-2">Department</label>
<input class="form-control col" type="text" placeholder="Department name" name="department_name" required/>
#foreach($errors->get('name') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>
<div class="form-group row align-items-center">
<label class="col-2">Faculty</label>
<select name="faculty_name" class="form-control col" required>
<option value="" selected>Select a Faculty</option>
#foreach($manage_faculties as $key => $cate_pro)
<option value="{{$cate_pro->id}}">{{$cate_pro->faculty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group row">
<label class="col-2">Description</label>
<textarea class="form-control col" rows="10" placeholder="Write something here..." name="description" required ></textarea>
</div>
</div>
<!--end of modal body-->
<div class="modal-footer">
<button role="button" class="btn btn-primary" type="submit">
Post
</button>
</div>
</div>
</form>
You can look here for displaying errors in Laravel.
Why did you put :
{{ $errors->get('name') ? 'has-error' : '' }}
inside a "div" like a attribute ?

why Dynamically add section doesn't work after retrieving the data from DB?

I have a button that adds a new language section to the form for the users to add a new language to their profile and it was working fine until I added that part which gets the existing user languages from DB to show in case they want to change the language or update it. I have been struggling for hours and can't figure out why is this happening why it stops working when the getUserLanguages function is being called. and when remove the getUserLanguages function from the render method it will start working again.
component controller:
public function addLanguage($i)
{
$i = $this->i;
if ($i <= 3)
{
$i = $i + 1;
$this->i = $i;
array_push($this->languages , ['language_name'=>'', 'language_level'=>'']);
}
else
{
$this->sweetAlert('error', 'You only can add 3 langauges.');
}
}
public function getUserLanguages()
{
if (empty(!UserLanguage::where('user_id', auth()->user())))
{
$this->languages = UserLanguage::where('user_id', auth()->user()->id)->get(['language_name', 'language_level'])->toArray();
$this->i = count($this->languages);
}
}
the view:
#foreach ($languages as $index)
<div class="card card-body mb-4">
<div class="row">
<div class="form-group col-md-6">
<label class="" for="languageName">Language</label>
<select class="form-control form-control-alternative" name="language-name" {{-- id="languageName" --}} wire:model="languages.{{ $loop->index }}.language_name">
<option value="" class="form-control" selected disabled>Select Language</option>
#foreach ($language_names as $name)
<option value="{{ $name->abbreviation }}" class="form-control">{{ $name->language }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-6">
<label class="" for="languageProficiency">Proficiency</label>
<select class="form-control form-control-alternative" name="language-proficiency" {{-- id="languageProficiency" --}} wire:model="languages.{{ $loop->index }}.language_level">
<option value="" class="form-control" selected disabled>Proficinecy Level</option>
#foreach ($language_levels as $level)
<option value="{{ $level->level }}" class="form-control">{{ $level->name }}</option>
#endforeach
</select>
</div>
</div>
</div>
#error('languages.*.level')
<small class="text-warning">{{ $message }}</small>
#enderror
#error('languages.*.language')
<small class="text-warning">{{ $message }}</small>
#enderror
#endforeach
#if (count($languages) < 3)
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-outline-secondary btn-round btn-block" wire:click="addLanguage({{$i}})"><span class="btn-inner--icon"><i class="fa fa-plus fa-2x"></i></span></button>
</div>
</div>
#endif
so finally after i called the getUserLanguages() from the mount method instead of the render method everything works as it should be.

updating the data in pivot table laravel 5

i have a many to many realtionship and a pivot table now i want to update the pivot table data with a form that users sends. here for example is assign a client to a sellman . here is my code :
in route :
Route::get('admin/client/assign','ClientController#assignsellman');
controller :
public function assignsellman(Request $request){
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client->sellmanlist()->attach($sellman);
return view('admin.client.assign',compact('client_list','user'));
}
and finally here is the form of view file that i want to get 2 variables one the id of the client and the secound the id of sell man
<form action="/admin/client/" method="post">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="client">مشتری</label>
<select class="select-search select2-hidden-accessible" tabindex="-1" aria-hidden="true"
name="client">
#foreach($client_list as $client_lists)
<option value="">{{$client_lists->title}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-4 text-center">
<i class="icon-arrow-left7 mr-3 icon-3x" style="font-size: 130px"></i>
<h4>ارجاع به</h4>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="form-group">
<label for="sellman">کارشناس فروش</label>
<select class="select-search select2-hidden-accessible" tabindex="-1"
aria-hidden="true" name="sellman">
#foreach($user as $users)
<option value="1">{{$users->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">تایید</button>
</form>
with this code i get this error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
thanks for help
Edit your route
Route::post('admin/client/','ClientController#assignsellman');
That is because the route you've created is HTTP GET, and in your form you're using HTTP Post.
<form action="/admin/client/" method="post">
Try switching to a GET method and it should work
<form action="/admin/client/" method="get">
or switch your route to
Route::post('admin/client/assign','ClientController#assignsellman');
Please take a look at the different HTTP Verbs and apply them to your needs.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Laravel - Form Action to Controller Function

I'm trying to create a situation where a user can load a page, select a timesheet number, and then have the system delete all records associated with that timesheet number. This function loads the form page:
public function deletetimesheetLoad()
{
$timesheets = collect(DB::select("SELECT dbo.TIME.Source AS Source
FROM dbo.TIME
GROUP BY dbo.TIME.Source
ORDER BY dbo.TIME.Source ASC"));
return view('utilities/deletetimesheet',['timesheets' => $timesheets]);
}
This is the actual blade template:
<form method="post"
action="{{url('/time/deletetimesheet/process')}}"
enctype="multipart/form-data"
<div class="form-group">
<label class="col-md-12 control-label" for="TIMESHEETNUMBER">Timesheet Number</label>
<div class="col-md-12">
<select required id="TIMESHEETNUMBER" name="TIMESHEETNUMBER" class="form-control select2_field">
<option value=""></option>
#foreach ($timesheets as $row)
<option value="{{ $row->Source }}">{{ $row->Source }}</option>
#endforeach
</select>
</div>
</div>
<div id="saveActions" class="form-group">
<input type="hidden" name="save_action" value="Submit">
<div class="btn-group">
<button type="submit" class="btn btn-success">
<span class="fa fa-save"></span>
<span data-value="Submit">Submit</span>
</button>
</div>
<span class="fa fa-ban"></span> Cancel
</div>
This is the function that the form action is pointing to:
public function deletetimesheetProcess(TimesheetRequest $request)
{
DB::table('TIME')->where('Source', $request->get('TIMESHEETNUMBER'))->delete();
\Alert::success(trans('yay'))->flash();
return view('details/customershow',[]);
}
Here are the defined routes for the two functions:
Route::get('/time/deletetimesheet', 'Admin\TimeCrudController#deletetimesheetLoad');
Route::post('/time/deletetimesheet/process', 'Admin\TimeCrudController#deletetimesheetProcess');
Currently the blade template loads correctly, and does not throw an error on submit - just reloads the current page. What am I doing wrong?

How i delete name of one image from name of images in array?

I have a Multiple images in array in row like:
["1.jpg","2.jpg"]
I need delete name of one image from name of images in array in db,
this is my form to show and delete submit:
#foreach(json_decode($post->images ,true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
<div class="portfolio-box">
<img src="public/img/offers/{{ $images }}" class="img-responsive"alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<form action="images/{{ $images }}/delete" method="get">
{!! csrf_field() !!}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</div>
</div>
</div>
</div>
#endforeach
and this is my Route:
Route::get('images/{images}/delete','DashboardController#deleteimg');
what i do in Controller ??
Pass post id in form
#foreach(json_decode($post->images ,true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
<div class="portfolio-box">
<img src="public/img/offers/{{ $images }}" class="img-responsive"alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<form action="images/{{ $images }}/delete" method="get">
{!! csrf_field() !!}
<input type="hidden" name="post_id" value="{{$post->id}}"/>
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</div>
</div>
</div>
</div>
#endforeach
And in controller
public function deleteimg($image,Request $req){
$post=Post::find($req['post_id']);
$images=json_decode($post->images);
$_image=[];
$_image[]=$image;
$post->images=json_encode(array_values(array_diff($images,$_image)));
$post->save();
return redirect()->back();
}
OR
public function deleteimg($image,Request $req){
$post=Post::find($req['post_id']);
$images=json_decode($post->images);
unset($images[$image]);
$post->images=json_encode(array_values(images));
$post->save();
return redirect()->back();
}

Categories