Laravel 6 - `Undefined variable: value` only error in the first time - php

In the first time I want to save data to database from table this error appear.
ErrorException
Undefined variable: value
so I have to manually input the data from tinker or mysql
My Controller
public function store(Request $request)
{
$validateData = $request->validate([
'name_device_type' => 'required|max:255',
'signature' => 'Nullable'
]);
$id = DeviceType::getidDeviceTypes();
foreach ($id as $value); // Error happend in this line.
$lastdevicetypeId = $value->id;
$newdevicetypeId = $lastdevicetypeId + 1;
$GetnewdevicetypeId = sprintf('DT%04d', $newdevicetypeId);
$devicetypes = new DeviceType();
$devicetypes->idDeviceType = $GetnewdevicetypeId;
$devicetypes->name_device_type = $request->input('name_device_type');
$devicetypes->signature = $request->input('signature');
$devicetypes->save();
return redirect('/devicetypes')->with('success', 'New Device Type is added');
}
My Migration table
public function up()
{
Schema::create('device_types', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('idDeviceType');
$table->string('name_device_type');
$table->mediumText('signature');
$table->timestamps();
});
}
My create.blade.php
{!! Form::open(['action' => 'DeviceTypesController#store', 'method' => 'POST']) !!}
<div class="form-group">
{!! Form::label('name_device_type', 'Type Device'); !!}
{!! Form::text('name_device_type', '', ['class' => 'form-control', 'placeholder' => 'Type Device']); !!}
</div>
<div class="form-group">
{!! Form::label('signature', 'Signature (Optional)'); !!}
{!! Form::textarea('signature', '', ['id' => 'classic-ckeditor5', 'class' => 'form-control', 'placeholder' => 'Signature']); !!}
</div>
{{ Form::button('<i class="far fa-save"></i> Submit', ['type' => 'submit', 'class' => 'btn btn-info'] ) }}
{!! Form::close() !!}
the Model
class DeviceType extends Model
{
// Table Name
protected $table = 'device_types';
// Primary Key
protected $primaryKey = 'idDeviceTypes';
// Timestamps
public $timestamps = true;
public $incrementing = false;
public static function getidDeviceType(){
return $getidDeviceType = DB::table('device_types')->orderBy('id','desc')->take(1)->get();
}
}
But if the table has data this error disappear, also this error will appear again if I remove every data and made the table empty.

You have a Semicolon right after the foreach loop definition: foreach ($id as $value);
and you are using the $value in the next line $lastdevicetypeId = $value->id; which is outside the scope of your loop.
You should remove the ; following the the foreach loop and change it to : and add a endforeach; where you want to end the loop.
Example:
foreach ($id as $value):
$lastdevicetypeId = $value->id;
$newdevicetypeId = $lastdevicetypeId + 1;
$GetnewdevicetypeId = sprintf('DT%04d', $newdevicetypeId);
$devicetypes = new DeviceType();
$devicetypes->idDeviceType = $GetnewdevicetypeId;
$devicetypes->name_device_type = $request->input('name_device_type');
$devicetypes->signature = $request->input('signature');
$devicetypes->save();
endforeach;
Or you can write this code as:
foreach ($id as $value){
$lastdevicetypeId = $value->id;
$newdevicetypeId = $lastdevicetypeId + 1;
$GetnewdevicetypeId = sprintf('DT%04d', $newdevicetypeId);
$devicetypes = new DeviceType();
$devicetypes->idDeviceType = $GetnewdevicetypeId;
$devicetypes->name_device_type = $request->input('name_device_type');
$devicetypes->signature = $request->input('signature');
$devicetypes->save();
}

You could grab the max 'id' of the table and add 1 to it without having to grab a whole record:
...
// validation
$newdevicetypeId = DeviceType::max('id') + 1;
$GetnewdevicetypeId = sprintf('DT%04d', $newdevicetypeId);
// new DeviceType
...
There is the option of having a model event that can set this particular field after the record has been created so it has its own id to use.

Related

How to display the last inserted id in db using Laravel after creating

Patient Controller:
public function store(Request $request)
{
$input = request()->all();
Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
}
This is my medical.create view
{!! Form::model($input, [
'method' => 'POST',
'action' => ['MedicalController#store', $input->id]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id', null, array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}
I want to get my last inserted id after storing, and display the last id in the next form, but this is the error appear in my screen:
Trying to get property 'id' of non-object
This is my Patient table:
You can do that by saving the Patient object in a variable when creating it:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input); // Save it in variable
dd($patient->id); //Now you can access patient id here
// return redirect()->route('medical.create',compact('patient')); //Also you can pass it to your view
}
you can use id like Code below with least Changes in your code
$input = request()->all();
$input = Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
you can retrive id after saving data by mass assignments :
public function store(Request $request)
{
$input = request()->all();
$patient = new Patient($input); // fill model with mass assignments
$patient->save() // save instant
$id = $patient->id; //retrive id
}
You can't use compact while redirecting. Try this:
Patient Controller:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input);
$patient = DB::table('patients')->get()->last();
return redirect()->route('medical.create')->with('patient_id', $patient->id);
}
This is my medical.create view
{!! Form::model($input, [
'method' => 'POST',
'action' => ['MedicalController#store', session('patient_id')]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id', null, array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}

How to pass $id of a form to another form

I have multiple forms where I need to pass through the id. In the example bellow I have 2 controllers one is for Courses and one is for the Exams. I'm trying to create a course and then pass through the course id to the exam form.
Here is what I've tried but the value is not passing through.
Course Controller:
public function store(StoreCoursesRequest $request)
{
if (! Gate::allows('course_create')) {
return abort(401);
}
$request = $this->saveFiles($request);
$course = Course::create($request->all()
// $status = array('assigned' => 'assigned', 'canceled'=>'canceled');
+ ['position' => Course::where('curriculum_id', $request->curriculum_id)->max('position') + 1]);
$trainers = \Auth::user()->isAdmin() ? array_filter((array)$request->input('trainers')) : [\Auth::user()->id];
$course->trainers()->sync($trainers);
$course->roles()->sync(array_filter((array)$request->input('roles')));
$course->assigned_user()->sync(array_filter((array)$request->input('assigned_user')));
$curriculum = Curriculum::get(array('id' => 'id'));
$exam = Exam::get(array('id' => 'id'));
foreach ($request->input('course_materials_id', []) as $index => $id) {
$model = config('medialibrary.media_model');
$file = $model::find($id);
$file->model_id = $course->id;
$file->save();
}
session('id', 'id');
return redirect()->route('admin.exams.create');
}
Here is the exams controller
public function create()
{
if (! Gate::allows('exam_create')) {
return abort(401);
}
$exam_assigneds = \App\Exam::get()->pluck('title', 'id')->prepend(trans('global.app_please_select'), '');
$questions = \App\ExamQuestion::get()->pluck('question', 'id');
$in_classes = \App\InClassCourse::get()->pluck('title', 'id')->prepend(trans('global.app_please_select'), '');
$reoccurance_type = \App\ReoccuranceType::get()->pluck('type', 'id')->prepend(trans('global.app_please_select'), '');
$courses = session('id');
return view('admin.exams.create', compact('courses', 'exam_assigneds', 'questions', 'in_classes', 'reoccurance_type'));
}
Here is the view
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('course_id', trans('global.exam.fields.course').'', ['class' => 'control-label']) !!}
{!! Form::text('id', $courses, old('id'), ['class' => 'form-control', 'placeholder' => '']) !!}
<p class="help-block"></p>
#if($errors->has('course_id'))
<p class="help-block">
{{ $errors->first('course_id') }}
</p>
#endif
</div>
</div>
All I'm getting is just text value of id. It doesn't pull the actual id.
In Course Controller modify
session('id', 'id');
to
session('id', $course->id);

'multipart/form-data' not working

I'm using Laravel and trying to build a gallery, i'm testing the upload of a file but i when i attach a file and click submit i can't get a positive outcome using the test set up. The code is below
GalleryController
// Store Gallery
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description', '');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if($cover_image){
die ('YES');
} else {
die ('NO');
}
}
The form is set up as follows
{!! Form::open(array('action' => 'GalleryController#store', 'enctype' => 'multipart/form-data')) !!}
{!! Form::label ('name', 'Name') !!}
{!! Form::text ('name', $value = null, $attributes = ['placeholder' => 'Gallery Name', 'name' => 'name']) !!}
{!! Form::label ('description', 'Description') !!}
{!! Form::text ('name', $value = null, $attributes = ['placeholder' => 'Gallery Description', 'name' => 'Description']) !!}
{!! Form::label ('cover_image', 'Cover Image') !!}
{!! Form::file('cover_image') !!}
{!! Form::submit ('Submit', $attributes = ['class' => 'button']) !!}
{!! Form::close() !!}
Any help is appreciated
Thanks
Your form looks correct, it is likely your controller where you are retrieving the uploaded file.
As per the docs, to retrieve an uploaded file you should use $request->file():
$request->file('cover_image');
That link to the docs above also goes on to explain how you can check the file properly and store the file.
//use input facades.
use File;
use Illuminate\Support\Facades\Input;
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description', '');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if(Input::hasFile('cover_image'){
die ('YES');
}
else {
die ('NO');
}
}

Laravel update makes new table rule instead of updating

I have a company table and an attributes table with all sorts of value in it.
One company hasMany attributes and an attribute belongsTo a company.
Now I have a value inside the attributes table with a 'account_nr_start' (for example, when a new user is added to a company its account_id starts counting up from 1000).
Controller:
public function __construct(Company $company, User $user)
{
if(Auth::user()->usertype_id == 7)
{
$this->company = $company;
}
else
{
$this->company_id = Auth::user()->company_id;
$this->company = $company->Where(function($query)
{
$query->where('id', '=', $this->company_id )
->orWhere('parent_id','=', $this->company_id);
}) ;
}
$this->user = $user;
$this->middleware('auth');
}
public function edit(Company $company, CompaniesController $companies)
{
$companies = $companies->getCompaniesName(Auth::user()->company_id);
$attributes = $company->attributes('company')
->where('attribute', '=', 'account_nr_start')
->get();
foreach ($attributes as $k => $v) {
$nr_start[] = $v->value;
}
return view('company.edit', ['company' => $company, 'id' => 'edit', 'companies' => $companies, 'nr_start' => $nr_start]);
}
public function update(UpdateCompanyRequest $request, $company, Attribute $attributes)
{
$company->fill($request->input())->save();
$attributes->fill($request->only('company_id', 'attribute_nr', 'value'))->save();
return redirect('company');
}
HTML/Blade:
<div class="form-group {{ $errors->has('_nr_') ? 'has-error' : '' }}">
{!! HTML::decode (Form::label('account_nr_start', trans('common.account_nr_start').'<span class="asterisk"> *</span>', ['class' => 'form-label col-sm-3 control-label text-capitalize'])) !!}
<div class="col-sm-6">
{!! Form::text('value', $nr_start[0], ["class"=>"form-control text-uppercase"]) !!}
{!! $errors->first('account_nr_start', '<span class="help-block">:message</span>') !!}
</div>
</div>
When I update a company now, it will upload like the last input here: :
So it makes a new rule, while it needs to edit the current attribute rule instead of making a new rule with an empty company_id/attribute.
If I understand what you are trying to do, I think this will fix your problem. The issue you have is the Attribute model is a new instance of the model rather than retrieving the model you need.
before running fill() from the attributes method try this
$new_attribute = $attributes->where('company_id', '=', $company->id)->where('attribute', '=', 'account_nr_start')->first();
Then run the fill()
$new_attribute->fill($request->only('company_id', 'attribute_nr', 'value'))->save();

Laravel error when hasOne has nothing

I am trying to pre-populate some fields in a form and I'm new to relationships.
My controller:
public function index($supplierId) {
$Supplier = new Supplier;
$supplierData = Supplier::find($supplierId);
$supplierData->countryId = ($supplierData->countryId == 0 ? 258 : $supplierData->countryId);
$supplierData->writtenLanguageId = ($supplierData->writtenLanguageId == 0 ? 1 : $supplierData->writtenLanguageId);
$supplierData->paymentTermsId = ($supplierData->paymentTermsId == 0 ? 5 : $supplierData->paymentTermsId);
$countries = Countries::lists('country', 'id');
$languages = Languages::lists('language', 'id');
$paymentTerms = PaymentTerms::lists('term', 'id');
$leadTimes = Leadtimes::lists('leadtime', 'id');
return View::make('supplier.supplier', array(
'supplierData' => $supplierData,
'countries' => $countries,
'languages' => $languages,
'paymentsTerms' => $paymentTerms,
'leadtimes' => $leadTimes
));
}
My model:
class Supplier extends Eloquent {
protected $table = 'suppliers';
public function email() {
return $this->hasOne('SupplierEmail', 'supplierId');
}
public function creditLimits() {
return $this->hasOne('SupplierCreditLimits', 'supplierId');
}
public function website() {
return $this->hasOne('SupplierWebsite', 'supplierId');
}
}
The problem:
<div class='col-xs-12 col-md-6'>{{Form::text('website', $supplierData->website->website, array('class' => 'form-control input-sm'))}}</div>
When there is no row (there is no record), I get:
Trying to get property of non-object (View: C:\wamp\vhosts\view\laravel\app\views\supplier\supplier.blade.php)
How do I get this to work properly?
In your view, use isset to check the value first:
<div class='col-xs-12 col-md-6'>
{{Form::text('website',
isset($supplierData->website->website) ? $supplierData->website->website : '',
array('class' => 'form-control input-sm'))
}}
</div>
Or, better yet, handle this logic in your controller and pass the result to the view:
$supplierData->URL = isset($supplierData->website->website) ? $supplierData->website->website : '';

Categories