Laravel , suddenly query error - laravel

I used a code in my Basecontroller to share data with all the views ( for footer and header informations ) , it worked great but suddenly i was working on something totally different and i've got an error : No query results for model [Variable]
Can't understand why i didn't even modify my BaseController.
Here is my Base Controller :
public function __construct(){
$this->getVariable('horaire');
$this->getVariable('facebook');
$this->getVariable('contact');
$this->getVariable('twitter');
$main_slider = MainSlider::all();
View::share('main_slider',$main_slider);
}
public function getVariable($setting)
{
$variables[$setting] = Variable::where('name', $setting)->FirstOrFail();
$values[$setting] = $variables[$setting]->value;
View::share($setting, $values[$setting]);
}
And what I was working on
Class VariablesController extends BaseController {
public function settings(){
$settings['about'] = Variable::where('name','about')->FirstOrFail();
$settings['contact'] = Variable::where('name','contact')->FirstOrFail();
$settings['horaire'] = Variable::where('name','horaire')->FirstOrFail();
$settings['legals'] = Variable::where('name','legals')->FirstOrFail();
$settings['facebook'] = Variable::where('name','facebook')->FirstOrFail();
$settings['twitter'] = Variable::where('name','twitter')->FirstOrFail();
$settings['contact_email'] = Variable::where('name','contact_email')->FirstOrFail();
return View::make('admin.settings',compact('settings'));
}
public function update(){
$inputs['facebook'] = e(Input::get('facebook'));
$inputs['twitter'] = e(Input::get('twitter'));
$inputs['contact_email'] = e(Input::get('contact_email'));
$inputs['legals'] = e(Input::get('legals'));
$inputs['horaire'] = e(Input::get('horaire'));
$inputs['contact'] = e(Input::get('contact'));
$inputs['about'] = e(Input::get('about'));
foreach($inputs as $name => $input){
echo "$name => $input";
}
}
And my Variable model :
<?php
class Variable extends \Eloquent {
protected $guarded = ['id','created_at','protected_at'];
protected $table = 'variables';
}
Thank you for your helps

Related

Codeigniter 4: Get value from BaseController to custom helper

Seems get_instance() is no longer working in Codeigniter 4. But I need to get some value from BaseController to my custom_helper. Here is my code snippet:
BaseController.php
<?php namespace App\Controllers;
class BaseController extends Controller
{
protected $helpers = ['custom'];
public function initController(...) {
parent::initController(...);
$myconfig = config('MyConfig');
$this->languages = $myconfig->languages;
$this->selected_lang = $myconfig->site_lang;
$lang_segment = $this->request->uri->getSegment(1);
foreach ($this->languages as $lang) {
if ($lang_segment == $lang->short_form) {
$this->selected_lang = $lang;
$this->lang_base_url = base_url() . $lang->short_form . "/";
}
}
}
}
// Here I need to pass ($this->selected_lang) value to my custom_helper.
custom_helper.php
<?php
if (!function_exists('trans')) {
function trans($string)
{
$language_translations = get_translation_array($this->selected_lang->id);
// --> Here I want to get ($this->selected_lang->id) value from BaseController.
if (!empty($language_translations[$string])) {
return $language_translations[$string];
}
return "";
}
}
function get_translation_array($land_id)
{
.......
}
I'm not sure is it possible or not! I'm newbie in CI4. Please suggest if is there any solutions. Thanks in advance.
Instead of calling the BaseController you should do everything within the helper that is
if (!function_exists('trans')) {
function trans($string)
{
$myconfig = config('MyConfig');
$languages = $myconfig->languages;
$selected_lang = $myconfig->site_lang;
$language_translations = get_translation_array($selected_lang->id);
if (!empty($language_translations[$string])) {
return $language_translations[$string];
}
return "";
}
}
Although I don't know what you are trying to do but I hope this will help you if not call my attentions again

Override CustomerFormatter.php for birthday form

I would like to put the birthday field mandatory, so I override the CustomerFormatter but it does not work at all. That's how I did:
<?php
class CustomerFormatter extends CustomerFormatterCore
{
public function getFormat()
{
$customerForm = parent::getFormat();
if ($customerForm->ask_for_birthdate) {
$format['birthday'] = (new FormField)
->setName('birthday')
->setType('text')
->setLabel(
$customerForm->translator->trans(
'Birthdate', [], 'Shop.Forms.Labels'
)
)
->addAvailableValue('placeholder', Tools::getDateFormat())
->addAvailableValue(
'comment',
$customerForm->translator->trans('(E.g.: %date_format%)', array('%date_format%' => Tools::formatDateStr('31 May 1970')), 'Shop.Forms.Help')
)
->setRequired(true)
;
}
}
}
I am under Prestashop 1.7.3.3
Do you have an idea of ​​the problem ? Thank you for your help
Probably to late for you but it might help others, this is unfortunately impossible with 1.7.
"Yes, overrides work as usual on all classes that have no namespace (so you can still override Product, Address, etc.)."
http://build.prestashop.com/news/prestashop-1-7-faq/#can-developers-still-use-overrides-in-17
You need to go to public_html/override/classes/form/ and create the file CustomerFormatter.php then type this code:
<?php
/**
* #Override CustomerFormatter
*/
use Symfony\Component\Translation\TranslatorInterface;
class CustomerFormatter extends CustomerFormatterCore
{
private $translator;
private $language;
private $ask_for_birthdate = true;
private $ask_for_password = true;
private $password_is_required = true;
private $ask_for_new_password = false;
public function __construct(
TranslatorInterface $translator,
Language $language
) {
parent::__construct($translator, $language);
$this->translator = $translator;
$this->language = $language;
}
public function getFormat()
{
$format = parent::getFormat();
$format = [];
if ($this->ask_for_birthdate) {
$format['birthday'] = (new FormField())
->setName('birthday')
->setType('birthday')
->setLabel(
$this->translator->trans(
'Birthdate',
[],
'Shop.Forms.Labels'
)
)
->setRequired($this->password_is_required);
}
}
You need to use:
->setRequired($this->password_is_required)
Because there's an error on checkout for guests purchases. So like this, it would be an optional field.

How would you do that with Eloquent - Laravel 5.2

I have this logic in a controller :
// hydratation part 1 (cf son modele)
$matiere->fill($request->all());
// hydratation part 2 with attributes not in the POST
$matiere->id_ecole = Session::get('id_ecole');
$request->has('matiere_inactive') ? $matiere->matiere_inactive = '1' : $matiere->matiere_inactive = null;
if ($matiere->exists) {
$matiere->auteur_modif = Session::get('nom').' '.Session::get('prenom');
} else {
$matiere->auteur_creation = Session::get('nom').' '.Session::get('prenom');
}
I think that the part 2 could be present in the model , instead of the controller (I like to have 'brief' controller).
Is it a good idea ?
If yes how could I do that ?
My model is :
class Matiere extends Model {
protected $table = 'matiere';
protected $primaryKey = 'id_matiere';
protected $fillable = [
'id_matiere',
'code_court_matiere',
'libelle_matiere'
];
public function setCodeCourtMatiereAttribute($value)
{
$this->attributes['code_court_matiere'] = strtoupper($value);
}
public function setLibelleMatiereAttribute($value)
{
$this->attributes['libelle_matiere'] = ucwords($value);
}
}
Laravel 5. 3
you can do that by creating a method on Matiere model.
Here is a simple example:
ExampleController.php
$mat = new \App\Matiere();
$feedback = $mat->addm($request);
Matiere.php
public function addm($request)
{
$this->id_ecole = \Session::get('id_ecole');
$request->has('matiere_inactive') ? $this->matiere_inactive = '1' : $this->matiere_inactive = null;
$this->save();
return $this->id;
}

Laravel get relationship model within object after save()

I am using laravel 4.2.
I have two models as below :
class User extends Eloquent{
protected $table = 'users';
public function user_card_details(){
return $this->hasMany('User_card_details');
}
}
And
class User_card_details extends Eloquent {
protected $table = 'user_card_details';
public $timestamps = true;
public $softdeletes = true;
public function user(){
return $this->belongsTo('User')->first();
}
}
And I can save the relationship record using :
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user->user_card_details()->save($user_card_details);
Up to this it works fine for me.
After save() , I want the user object should be populated with user_details.
So if I want to use the properties, I can use it like :
echo $user->user_card_details->card_number;
But it is not working now.
Any suggestions?
Thanks
You have to remove the () to get the actual model or collection:
echo $user->user_card_details->card_number;
When you're calling the actual function, you'll receive an instance of the Query builder.
Also, it seems that you're not persisting your $user_card_details-object before you try to bind it to your user:
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user_card_details->save(); //Added this line.
$user->user_card_details()->save($user_card_details);
The more correct way would be:
$user_card_details = [
'card_number' => Input::get( 'card_number' ),
'card_exp_month' => Input::get( 'card_expires_m' ),
'card_exp_year' => Input::get( 'card_expires_y' ),
'card_cvv' => Input::get( 'card_cvv' ),
];
$userCardDetailObj = $user->user_card_details()->create( $user_card_details );
Now, your User_card_detail-instance will be available as the returned object.

How to cache model attributes in Laravel

In my current configuration, a user's email is stored on a remote server that I need to hit with a curl quest.
Luckily, I only need the email once a day when a certain process runs. However, when that process does run it will need to reference the email multiple times.
This is the current accessor I have set up for email. The problem is the curl request is being called every time I use $user->email. What's the best way to avoid this?
in UserModel:
public function getEmailAttribute(){
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
private $cached_email = false;
public function getEmailAttribute(){
if ($this->cached_email){
// if set return cached value
return $this->cached_email;
}
// get the email
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
// cache the value
$this->cached_email = $response->email;
// and return
return $this->cached_email;
}
Depending on your use case make adjustments (ie. session, cache , static property...).
Extend a the Eloquent Model class
namespace App\Models\Utils;
use Illuminate\Database\Eloquent\Model as OldModel;
class MyModel extends OldModel
{
private $cachedAttributes = [];
public function getCachedAttribute(string $key, Callable $callable)
{
if (!array_key_exists($key, $this->cachedAttributes)) {
$this->setCachedAttribute($key, call_user_func($callable));
}
return $this->cachedAttributes[$key];
}
public function setCachedAttribute(string $key, $value)
{
return $this->cachedAttributes[$key] = $value;
}
public function refresh()
{
unset($this->cachedAttributes);
return parent::refresh();
}
}
make your class
class ElementWithEmail extends MyModel
{
const ATTRIBUTE_KEY_FOR_EMAIL = 'Email';
public function getEmailAttribute(){
$key = self::ATTRIBUTE_KEY_FOR_EMAIL;
$callable = [$this, 'getEmail'];
return $this->getCachedAttribute($key, $callable);
}
protected function getEmail()
{
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
}
Call it from your code
$element = new ElementWithEmail();
echo $element->email;

Resources