Relationship hasone trying to get property of non-object - laravel

I got a problem with relationship one to one mechanism for edit & update condition, so I have model Siswa and Telepon, with Telepon belongs to Siswa... here is the code
Siswa.php (model)
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tgl_lahir',
'jns_klmin'
];
protected $dates = ['tgl_lahir'];
public function getNamaSiswaAttribute($nama_siswa){
return ucwords($nama_siswa);
}
public function setNamaSiswaAttribute($nama_siswa){
$this->attributes['nama_siswa']=ucwords($nama_siswa);
}
public function telepon(){
return $this->hasOne('App\Telepon', 'id_siswa');
}
}
Telepon.php (model)
class Telepon extends Model
{
protected $table = 'telepon';
protected $primKey = 'id_siswa';
protected $fillable = [
'id_siswa',
'no_telepon',
];
public function siswa(){
return $this->belongsTo('App\Siswa', 'id_siswa');
}
}
Edit and update function controller shown as follows :
public function edit($id){
$siswa = Siswa::findOrFail($id);
$siswa->no_telepon = $siswa->telepon->no_telepon;
return view('siswa.edit', compact('siswa'));
}
public function update(Request $request, $id){
$siswa = Siswa::findOrFail($id);
$input = $request->all();
$validator = Validator::make($input, [
'nisn'=>'required|string|size:4|unique:siswa,nisn,'.$request->input('id'),
'nama_siswa'=>'required|string|max:30',
'tgl_lahir'=>'required|date',
'jns_klmin'=>'required|in:L,P',
'no_telepon'=>'sometimes|numeric|digits_between:10,15|unique:telepon,no_telepon,'.$request->input('id').',id_siswa',
]);
if ($validator->fails()) {
return redirect('siswa/'.$id.'/edit')->withInput()->withErrors($validator);
}
$siswa->update($request->all());
$telepon = $siswa->telepon;
$telepon->no_telepon = $request->input('no_telepon');
$siswa->telepon()->save($telepon);
return redirect('siswa');
}
I got Trying to get property of non-object error in edit function, line "$siswa->no_telepon = $siswa->telepon->no_telepon;".
When we call edit view inside edit controller, it will give a form which inside of it has previous saved data. no_telepon itself is a column from Telepon table, not Siswa, so how to show telephone saved data for editing purposes is the problem. FYI, create works just fine, and no_telepon data saved in Telepon table. So, how about this one? Any help appreciated.

It's probably because you don't have any 'App\Telepon' in the database with 'id_siswa' pointing to the id of the record from table siswa.
You can ommit this error in this way:
public function edit($id){
$siswa = Siswa::findOrFail($id);
$siswa->no_telepon = $siswa->telepon ? $siswa->telepon->no_telepon : '';
return view('siswa.edit', compact('siswa'));
}

Related

laravel update() is not working on some models

I am trying to update the database record but Laravel update() function is not working. I have fillable array in the model. but still, it is not working.
The Property Model:
class Property extends Model
{
use HasFactory;
protected $table = 'properties';
protected $primaryKey = 'proID';
public $timestamps = false;
protected $fillable = [ 'proID', 'ProStatus', 'ProPurpose', 'ProType', 'SubType', 'basePrice', 'unitPrice', 'Width', 'Length', 'LandArea','PropertyNumber', 'water', 'electricity', 'gas', 'severage', 'fk_Street', 'createdBy', 'delete'];
public function streets(){
return $this->belongsTo(Street::class,'fk_Street');
}
public function hasInstallments(){
return $this->hasMany(Installments::class,'proID');
}
The PropertyController:
public function destroy($id)
{
$property = Property::find($id);
$property->delete = true;
if($property->save()){
return response()->json(['success'=>true]);
}
}
the $property->update() always returns true but record does not update in database.
The method update() is for mass update wich require an array of attributes and bypass mutators.
public function destroy($id)
{
$property = Property::find($id);
$property->update(['delete' => 1]);
}
You might want to use save() instead
public function destroy($id)
{
$property = Property::find($id);
$property->delete = 1;
$property->save();
}
Both will update the record, you'll need to implement your method's return logic on top of this code but as for updating the record, I think you get the idea.
Your property table primary key is "proID"
public function destroy($id)
{
$property = Property::where('proID', $id)->first();
if($property->update(['delete' => 1])) {
return response()->json(['success' => true]);
}
}

Insert data into custom table using resource model and block class

i am new in magento2. i have retrieve records from table and showed in grid but now i am trying to Insert/data in a custom table from a form but not getting any help. Can you pls guide me how can i Insert data in custom table using block class and resource model etc. i mean standard way to insert data.
Here is block class
class Insert extends Template
{
private $collectionFactory;
public $successMessage=null;
protected $data;
public function __construct(
Template\Context $context,
CollectionFactory $collectionFactory,
array $data = []
) {
$this->collectionFactory = $collectionFactory;
parent::__construct($context, $data);
}
public function execute()
{
$name = $this->getRequest()->getParam('bookName');
$author = $this->getRequest()->getParam('bookAuthor');
$description = $this->getRequest()->getParam('bookDescription');
$model = $this->collectionFactory->create();
$model->load($name);
$model->load($author);
$model->load($description);*/
$input = $this->getRequest()->getPostValue();
$model->setData($input);
$model->save();
$successMessage="Saved Successfully!";
}
}
-----------These are model classes---------------
class Book extends AbstractModel
{
protected function _construct()
{
$this->_init(\Vendor\BooksModule\Model\ResourceModel\Book::class);
}
}
class Book extends AbstractDb
{
protected function _construct()
{
$this->_init('Vendor_BooksModule_Book', 'id');
}
}
----------------This is resource model-----------------
class Collection extends AbstractCollection
{
protected $_idFieldName = 'id';
protected function _construct()
{
$this->_init("Vendor\BooksModule\Model\Book","Vendor\BooksModule\Model\ResourceModel\Book");
}
}
Thank you
First, need to create a customer module. some instruction here https://www.mageplaza.com/magento-2-module-development/how-create-hello-world-module-magento-2.html
After creating a custom module you need a create your custom table. and resource model using that link. https://www.mageplaza.com/magento-2-module-development/how-to-create-crud-model-magento-2.html
After creating a table and model you can save data inside a block. Inside block can data using getParam. But want to change like that.
public function execute()
{
$name = $this->getRequest()->getParam('bookName');
$author = $this->getRequest()->getParam('bookAuthor');
$description = $this->getRequest()->getParam('bookDescription');
$model = $this->collectionFactory->create();
$model = $model->getCollection()->addFieldToFilter('bookName', $name)->addFieldToFilter('bookAuthor', $author)->addFieldToFilter('bookDescription', $description);
$input = $this->getRequest()->getPostValue();
$model->setData($input);
$model->save();
$successMessage="Saved Successfully!";
}
We can collection only load with id. that is wrong you done. When use setData you also want to add attribute name. check and change that.

Creating a new record using a One to Many relation in Laravel

I have a sample relation between two models, User and Announcement as displayed below.
class Announcement extends Model
{
//
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
}
class User extends Model
{
//
protected $guarded = [];
public function announcements(){
return $this->hasMany(Announcement::class);
}
}
Currently I am trying to create a new announcement, using the relation but it throws an error
"message": "Call to a member function announcements() on null",
This is the current state of my api from the controller
class AnnouncementController extends Controller
{
public function store(Request $request)
{
//
$record = request()->user()->announcements()->create($this->validateRequest());
return (new AnnouncementResoure($record))
->response()
->setStatusCode(Response::HTTP_CREATED);
}
private function validateRequest()
{
return request()->validate([
'title'=> 'required|Min:3',
'comment' => 'required'
]);
}
}
I don't seem to know what could e responsible for the error.
instead of request()->user() replace it with auth('api')->user(); or $request->user('api');

Trying to get property of non - object Laravel 5.4

im still newbie, and trying to save data from REAXML file.
vendor for parsing REAXML from https://github.com/i4ucode/reaxml
Route:
Route::get('/admin/synctest', 'Admin\\AdminController#synctest');
Model Property
class Property extends Model
{
protected $table = 'properties';
protected $primaryKey = 'id';
protected $fillable = ['refID', 'propkind_id', 'other column'];
public function Kind()
{
return Propkind::findOrfail($this->propkind_id)->name;
}
//other public function
}
Model Propkind
class Propkind extends Model
{
protected $table = 'propkinds';
protected $primaryKey = 'id';
protected $fillable = ['id', 'name', 'slug'];
public function Property(){
return $this->hasMany('App\Property');
}
//other public function
}
Controller
public function synctest()
{
// get new class
$processor = new \REA\XmlProcessor();
$directories = Storage::disk('reaxml')->files();
foreach ($directories as $zipFile) {
//get XML file
$files = file_get_contents(url('feed/' . $zipFile));
//process the xml
$properties = $processor->parseXmlString($files);
//loop
foreach ($properties as $property) {
Property::updateOrCreate(
['refID' => $property->getRefID()],
[
//other code
'propkind_id' => Propkind::where('name', $property->getCategoryNaskleng())->first()->id, ===> ErrorException (E_NOTICE) Trying to get property of non-object
]
);
}
}
}
this piece of code Propkind::where('name', $property->getCategoryNaskleng())->first()->id)
==>show data but trow
ErrorException Trying to get property of non-object.
some kind of enlightenment, wisdom, very appreciate.
the difference between dd() and dump() is that dd() stops the execution of the script (die), dump() shows a representation of the argument but it doesn't stop the script.
for this reason I guess that the error (notice) comes after the excution of this piece of code you have posted.
clearly one of the values of $properties doesn't return a model
after several hours i found that null is the problem.
thank you #Devon for insight. #simonecosci and #Leena Patel for your comment.

Error "Creating default object from empty value" Laravel update using one-to-one database

I have one-to-one database. It's Telepon in different table. So, every 'siswa' has one 'telepon' (telephon number). Telepon has 'sometimes' type not 'required'. It can be blank.
But, if it set blank, error "Creating default object from empty value" appears when i do update.
Code in Telepon Model :
class Telepon extends Model
{
protected $table = 'telepon';
protected $primaryKey = 'id_siswa';
protected $fillable = [
'id_siswa',
'nomor_telepon',
];
public function siswa() {
return $this->belongsTo('App\Siswa', 'id_siswa');
}
Code in Siswa Model for Telepon:
public function telepon() {
return $this->hasOne('App\Telepon', 'id_siswa');
}
This in Controller for update:
public function update(Siswa $siswa, SiswaRequest $request){
$input = $request->all();
$siswa->update($input);
$telepon = $siswa->telepon;
$telepon->nomor_telepon = $request->input('nomor_telepon');
$siswa->telepon()->save($telepon);
$siswa->hobi()->sync($request->input('hobi_siswa'));
return redirect('siswa');
}
Use the null coalesce operator ?? to check for null or create a new model instance:
$telepon = $siswa->telepon ?? new Telepon();

Resources