professional way add data in database laravel 5.2 - mysql

what is the professional way insert record in database.
i am using laravel 5.2.
i'm new in laravel.
class students extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('student');
}
public function fees()
{
$record = array(
"p_name" => Input::get("name"),
"p_fees" => Input::get("fees"),
"p_detail" => Input::get("detail")
);
return view('fee');
}
}
stander able way?

You should use mass assignment. Fill $fillable array inside your model and use this:
Model::create($insertData);

public function store_student(Request $request)
{
$student = new Student;
$student->name = $request->name;
$student->detail = $request->details
$student->save();
return view('student');
}
public function store_fee(Request $request)
{
$fee = new Fee;
$fee->p_name = $request->name;
$fee->p_fee = $request->fees;
$fee->p_detail = $request->details
$fee->save();
return view('fee');
}

I suggest you to read this from Laravel official guide.
However you can do it like this:
DB::table('tablename')->insert($insertData);

Related

Laravel 5.8 show data of the another table like join

I need how to show data in another table like MySQL join or something like that
MySQL example
My Code
Model usuarios
class Usuario extends Model {
protected $table = 'usuarios';
protected $primaryKey = 'idusuarios';
protected $filliable = [
'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
];
public function Usuario() {
return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
}
const CREATED_AT = NULL;
const UPDATED_AT = NULL;
}
Model Roles
class Roles extends Model {
protected $table ='roles';
protected $primarykey = 'idrole';
protected $filliable = ['desc_rol'];
public function Roles() {
return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
}
}
Controller usuarios
public function index(Request $request) {
if (!$request->ajax()) return redirect('/');
$usuarios = Usuario::all();
return $usuarios;
}
View usuarios
that's what I need
Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
return [
'field1' => $role->field1,
'field2' => $role->field2,
'field3' => $role->field3,
'field4' => $role->field4,
'field5' => $role->field5,
'rol' => $role->Usuario->desc_role
];
});

Symfony 2.7 dateTime deserialize

I need some help with SF 2.7 serializer
I have made an API with get Json Data like this :
{
"dateDebut":"2017-02-16",
"dateFin":"2018-02-16",
"caMoisTotalHorsSessions":"5.2",
"caMoisClients":"5.3",
"caMoisGarantie":"5.4",
"caMoisHuile":"5.5" }
I tried many way in order to deserialze into my object Class where dateDebut and dateFin are attending to be Datetime object and not string
try {
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($date) {
return new \DateTime($date);
};
$normalizer->setCallbacks(array(
'dateDebut' => $callback,
'dateFin' => $callback, ));
$serializer = new Serializer(array($normalizer), array($encoder));
$entity = $serializer->deserialize($request->getContent(), $class, $format);
} catch (RuntimeException $e) {
return new JsonResponse(
['code' => Response::HTTP_BAD_REQUEST, 'message' => $this->trans('api.message.data_error')],
Response::HTTP_BAD_REQUEST);
}
But callbacks are never used :/ Could anyone help me please ?
Aim is to transform date string into Datetime object automatically before flush the object in database.
Thanks a lot
What you are trying to do is denormalization. The normalizer callbacks are for normalization. I think it's pretty confusing. It's strange that they would offer setting callback for just one direction.
I tested some code doing what I think you want to do. You need a custom normalizer class. The class is not so complicated, it can extend from the GetSetNormalizer or the ObjectNormalizer. You just want to create the \DateTime inside here, and you might add some validation for the date time.
class BoardNormalizer extends GetSetMethodNormalizer
{
public function denormalize($data, $class, $format = null, array $context = array())
{
if (isset($data['created'])) {
$data['created'] = new \DateTime($data['created']);
}
return parent::denormalize($data, $class, $format, $context);
}
}
I tested it with this code:
$json = json_encode([
'created' => '2017-02-20T05:49:51-0500'
]);
$encoder = new JsonEncoder();
$normalizer = new MyCustomNormalizer();
$serializer = new Serializer([$normalizer], [$encoder]);
$entity = $serializer->deserialize($json, MyCustomClass::class, 'json');
And it produced my custom class where the created property was a \DateTime object.
Aim is to transform date string into Datetime object automatically before flush the object in database.
Something like this? Using setters/getters ? I'm using the following code in entity
private $created;
public function setCreated($created)
{
if (!($created instanceof \DateTime)) {
$created = date_create($created);
}
$this->created = $created;
return $this;
}

How to passing parameter to afterSave() Method in yii2?

I'm new to yii2. I want to write afterSave() method after insert new record. My scenario is: when the user add a damage must be send email to him.
When user add damage, does not enter the serial number. I should read his name and serial damage but I don't know how to passing serial from Controller to model.
Damage Model:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$name = $this->user->name;
$serial = ?
$to = $this->user->email;
$subject = 'new damage';
$body = 'mr'.$name.'your damage with serial number'.$serial.'is registered';
if ($insert) {
App::sendMail($to, $subject, $body);
}
}
DamageController:
public function actionAddDamage($serial){
$model = new Damage();
$gaurantee = Gaurantee::find()->where(['serial' => $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
if (!$gaurantee)
throw new ForbiddenHttpException('You don't access');
$model->gr_id = $gaurantee->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('addDamage',
['model' => $model,
'servers' => $servers,
'gaurantee' => $gaurantee,
]);
}
public function init(){
$this->on(self::EVENT_AFTER_INSERT, [$this, 'sendMail']);
}
public function sendMail($event) {
}
First that comes to mind is to add attribute in damage model.
//Damage model
public $serial;
Then in your controller you can set value for this:
public function actionAddDamage($serial){
$model = new Damage();
$gaurantee = Gaurantee::find()->where(['serial' => $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
if (!$gaurantee)
throw new ForbiddenHttpException("you don't access");
$model->serial = $serial;
.....
In your afterSave() method you will have your serial as $this->serial.
2nd way is to get it from guaranty table since you have $this->gr_id , but this will generate 1 more db request.
You can create a property $serial in your Damage Model and assign the serial value to the $model->serial property in your Controller. For Example:
class Damage extends yii\db\ActiveRecord
{
public $serial = null;
public function afterSave($insert, $changeAttributes) {
// ...
var_dump($this->serial);
}
}
And in the controller you can assign $serial to the model:
public function actionAddDamage($serial) {
$model = new Damage();
$model->serial = $serial;
// ...
}

Yii2, Model find() with custom attribute

I want to pull the model data with custom attribute that assigned in a function in model.
Example)
class Test extends ActiveRecord
{
public static function tableName()
{
return '{{%test}}';
}
public function rules()
{
//....
}
public function attributeLabels()
{
return [
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
];
}
public function getFullName()
{
$fullName = $this->first_name.' '.$this->last_name;
return $fullName;
}
}
Test::find().with('fullName') => it doesn't work
How can I get all the data with fullname attribute?
with is for relations. You can get fullname attribute just by calling $model->fullName. Actually fullName is not an attribute, yii2 utilise php's magic method __get() to get it from getFullName() method.
Example:
$model = Test::findOne($id);
echo $model->fullName;
Example 2:
$models = Test::find()->all();
foreach($models as $model)
{
echo $model->fullName;
}
Also consider using of fields/extraFields methods if you want use your models as arrays instead of objects

Mysql functions in zend 2

How to query below in zend 2
select * from states st where TRIM(LOWER(st.state_name))='noida'
Any help is appreciated.
Thanks
/* DB Adapter get and SQL object create */
$adapter = GlobalAdapterFeature::getStaticAdapter();
$sql = new \Zend\Db\Sql\Sql($adapter);
/* Select object create */
$select = new \Zend\Db\Sql\Select();
$select->from('states');
$select->where->addPredicate(
new \Zend\Db\Sql\Predicate\Expression(
'TRIM(LOWER(state_name)) = ?',
'noida'
)
);
/* Select object convert to string and execute */
$queryString = $sql->getSqlStringForSqlObject($select);
$result = $adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
Use following:
$resultStates=$this->states->select()->where('TRIM(LOWER(st.state_name))=?','noida')
->query()
->fetchAll();
For details refer Here and Here.
In you model file just use below code here I am using module profile.
Profile/Model/Common.php
namespace Profile\Model;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
class Common
{
protected $dbConfig;
protected $adapter;
public function __construct($dbConfig)
{
$this->adapter = new Adapter($dbConfig);
}
public function getStateList()
{
$sql = "select * from states st where TRIM(LOWER(st.state_name))='noida'";
$statement = $this->adapter->query($sql);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$list = $resultSet->toArray();
return $list; // This will return a list of array
}
}
Profile/Controller/IndexController
namespace Profile\Controller;
use Profile\Model\Common;
class IndexController extends AbstractActionController
{
protected $dbConfig = array(
'driver' => DRIVER,
'database' => DB,
'username' => DBUSER,
'password' => DBPASS
);
public function init(){
$ssOrder = new Container(__CLASS__);
//SET OPTIONS
}
public function indexAction()
{
$plist = new Common($this->dbConfig);
$resultList = $plist->getStateList(); // This will give you state list
}
}
Good Luck