Insert data into custom table using resource model and block class - magento

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.

Related

Attach relation data directly to model

Article model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model
{
protected $table = 'articles';
protected $primaryKey = 'idArticle';
protected $fillable = [
'idArticle', 'Topic', 'Image', 'Content', 'Views',
];
protected $hidden = [
'idCategory', 'idUser',
];
public function category()
{
return $this->hasOne(Categories::class, 'idCategory', 'idCategory');
}
}
So now when i call $article = Articles::find(1);, it will returns data from articles table, when i add $article->category;, it adds data $article->category->Name. I would like to have that Name directly inside $article - something like $article->category (so $article->category->Name into $article->category) is it possible to define that just using model class or i need to map it inside controller?
You can assign custom attributes to your Model classes. But you can't use the same property name as your category() method, because it's already accessed by $article->category.
An example giving you a property called category_name
class Articles extends Model
{
// attributes to append to JSON responses
protected $appends = ['category_name'];
// ... your other properties and methods
// your custom attribute
public function getCategoryNameAttribute()
{
if (!is_null($this->category)) {
return $this->category->Name;
}
return '';
}
}
Use as:
$article->category_name
You can use appends, as mentioned by #matticustard or just use the ->with() method while retrieving your model:
$article = Articles::find($id)->with('category');
Then, you can access the category name with:
$categoryName = $article->category->name;
Hope it helps.

Relationship hasone trying to get property of non-object

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'));
}

how to get last id when a row was insert in laravel eloquent in Model

I've used setNotification method of model by initial data from Controller within a variable $data as array. I have used self:: in this method instead of used table or Notification::save() or $obj->save(). by this way I don't know how to get Id which the last id after insert was done in laravel because I used $this->attributes that it is the protected variable in Model.
class Notification extends Model
{
protected $table = 'notification';
public $timestamps = true;
private $_data = false;
public function setNotification($data)
{
if (is_array($data)) {
$this->attributes = $data;
self::save();
}
}
}
Try something like $this->attributes[id] after save() is executed.
I suggest You to use create method instead and return created object, so then You can access id property.
public function setNotification($data)
{
if (is_array($data)) {
return $this->create($data);
}
return null;
}

Comment/Post system in Laravel

I can't seem to get relationships concrete in my head with Laravel. Having tried to follow the docs for eloquent orm, I still can't get my foreign keys to mean something (I update them manually). Right now I am trying to get a bulletin board system to work. A user can create a bulletin post, and here it is working in my controller:
public function editPost($id)
{
$user = User::find($id);
$user->bulletin = new Bulletin;//new post
$user->bulletin->creator_id = $id;//why doesn't it automatically update given the relationship?
$user->bulletin->type = Input::get('type');
$user->bulletin->title = Input::get('title');
$user->bulletin->content = Input::get('bulletinEdit');
$user->bulletin->save();
if(Input::hasFile('bulletinImage')){
$extension = Input::file('bulletinImage')->getClientOriginalExtension();
$fileName = str_random(9).'.'.$extension;
$user->bulletin->photo = new Photo;
$user->bulletin->photo->user_id = $id;
$user->bulletin->photo->type = Input::get('type');
$user->bulletin->photo->filename = $fileName;
$user->bulletin->photo->touch();
$user->bulletin->photo->save();
Input::file('bulletinImage')->move('public/images/bulletin/',$fileName);
}
return Redirect::to('bulletin');
}
If I have the relationship set up properly, shouldn't the creator_id be updated automatically? Here is what I have in my models:
Bulletin
<?php
class Bulletin extends Eloquent {
public function creator()
{
return $this->belongsTo('User');
}
public function comments()
{
return $this->hasMany('Comment');
}
public function type()
{
//if 1 then, etc
}
public function photos(){
return $this->hasMany('Photo');
}
}
User
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function tags()
{
//TO REMOVE RECORD
//User::find(1)->tags()->detach();
return $this->belongsToMany('Tag');
}
public function createUser()
{
$password = Hash::make('secret');
}
public function bulletin()
{
return $this->hasMany('Bulletin','creator_id');
}
public function profile()
{
return $this->hasOne('Profile');
}
}
Could anybody give me some tips on tightening this up?
The way you are doing it should work, you are just using more code and Eloquent has some methods to help you attach relationships, so I would try something like this:
public function editPost($id)
{
$user = User::find($id);
// Create a new bulletin, passing the necesssary data
$bulletin = new Bulletin(Input::only(['type', 'title', 'bulletinEdit']));
// Attach the bulletin model to your user, Laravel should set the creator_id itself
$bulletin = $user->bulletin()->save($bulletin);
...
return Redirect::to('bulletin');
}
In your model, you'll have to:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = ['type', 'title', 'bulletinEdit'];
...
}
So Laravel doesn't give you a MassAssignmentException.

Laravel4 - Saving a model with multiple relationships/foreign keys

I've tried to understand a process of saving a model with multiple relationships but I still can't figure out how to do it "kosher" way.
To begin with - I have an Event model that belongs to a category (Eventcat) and a Location:
// Event.php
class Event extends Eloquent {
protected $table = 'events';
public function location()
{
return $this->belongsTo('Location');
}
public function eventcat()
{
return $this->belongsTo('Eventcat');
}
public function users()
{
return $this->belongsToMany('User');
}
}
// Location.php
class Location extends Eloquent
{
protected $table = 'locations';
public function events()
{
return $this->hasMany('Event');
}
}
// Eventcat.php
class Eventcat extends Eloquent
{
protected $table = 'eventcats';
public function events()
{
return $this->hasMany('Event');
}
}
I've seeded the database with a few categories and locations and now I trying to get events saving work. I thought that the $event->eventcat()->associate( $eventcat ) would work but I got a Call to undefined method eventcat() error.
public function postCreateEvent() {
$event = new Event();
$eventcat = Eventcat::find( Input::get('event-create-eventcat[]') );
$location = Location::find( Input::get('event-create-location[]') );
$event->title = Input::get('event-create-title');
$event->description = Input::get('event-create-description');
$event->price = Input::get('event-create-price');
$event->start_date = Input::get('event-create-start_date');
$event->end_date = Input::get('event-create-end_date');
$event->eventcat()->associate( $eventcat );
$event->location()->associate( $location );
$event->save();
}
I've read the documentation, API and a few threads here but I still can't figure out the best way to deal with this.
Thanks for replies!
I would actually bet that you have a conflict in your class name. Laravel contains an Event class and I wonder if that isn't what's being called in your code. As a quick test, you could rename your class FooEvent and see if it works.
The best solution is probably namespacing your model (see http://chrishayes.ca/blog/code/laravel-4-methods-staying-organized for a quick intro) so that your model can still be called Event without conflicting with the builtin class.

Resources