I'm having an issue with Eloquent. I am returning an object that contains data but when trying to access the id of the returned field it's blank.
Here's some example code:
public function activateMobile($token)
{
/*
* Get mobile activation row matching $token
*/
$activation = $this->ci->ActivationRepository->getMobileActivationByToken($token);
/*
* Does it exist?
*/
if(empty($activation)) {
return false;
}
die($activation);
}
And here's the model:
<?php
namespace MyApp\Models;
use Illuminate\Database\Eloquent\Model;
class MobileVerification extends Model
{
protected $table = 'mobile_verification';
public function user()
{
return $this->belongsTo('\MyApp\Models\User');
}
}
For examples sake I used die to print the value of the object in string form:
{"id":7,"user_id":24,"token":"68gb","is_used":0,"verified_at":null,"created_at":"2016-11-28 18:53:52","updated_at":"2016-11-28 18:53:52"}
As you can see the id is there.
But, if I replace the die with die($activation->id) its blank. Yet, if I do die($activation->token) that's visible.
Why is the id returning blank?
Related
I'm new to Laravel we are trying to add (https://github.com/TomLingham/Laravel-Searchy) to our project (https://github.com/wvulibraries/rockefeller-css/tree/trying-searchy) to allow the search of multiple fields in a table. I can see the package is in the vendor folder as tom-lingham for some reason I am not able to even use it. I get FatalThrowableError in DataViewController.php line 79: Class 'App\http\Controllers\Search' not Found. I followed the instructions in the github repo. Any suggestions would be appreciated.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Import the table and collection models
use App\Table;
use App\Collection;
use Illuminate\Support\Facades\Auth;
/**
* The controller is responsible for showing the cards data
*/
class DataViewController extends Controller {
/**
* Constructor that associates the middlewares
*
* #return void
*/
public function __construct(){
// Middleware to check for authenticated
$this->middleware('auth');
}
/**
* Show the data from the selected table
*/
public function index(Request $request, $curTable){
// Get the table entry in meta table "tables"
$curTable = Table::find($curTable);
if(!$curTable->hasAccess){
return redirect()->route('home')->withErrors(['Table is disabled']);
}
// Get and return of table doesn't have any records
$numOfRcrds = DB::table($curTable->tblNme)->count();
// check for the number of records
if ($numOfRcrds == 0){
return redirect()->route('home')->withErrors(['Table does not have any records.']);
}
// Get the records 30 at a time
$rcrds = DB::table($curTable->tblNme)->paginate(30);
// retrieve the column names
$clmnNmes = DB::getSchemaBuilder()->getColumnListing($curTable->tblNme);
// return the index page
return view('user.data')->with('rcrds',$rcrds)
->with('clmnNmes',$clmnNmes)
->with('tblNme',$curTable->tblNme)
->with('tblId',$curTable);
}
public function show(Request $request, $curTable, $curId){
// Get the table entry in meta table "tables"
$curTable = Table::find($curTable);
if(!$curTable->hasAccess){
return redirect()->route('home')->withErrors(['Table is disabled']);
}
// Check if search string and column were passed
if (strlen($curId) != 0) {
$numOfRcrds = DB::table($curTable->tblNme)
->where('id', '=', $curId)
->count();
// check for the number of records
if ($numOfRcrds == 0){
return redirect()->route('home')->withErrors(['Search Yeilded No Results']);
}
else {
// $rcrds = DB::table($curTable->tblNme)
// ->where('id', '=', $curId)
// ->get();
$rcrds = Searchy::search($curTable->tblNme)->fields('id')->query($curId)->get();
}
}
else {
return redirect()->route('home')->withErrors(['Invalid ID']);
}
// retrieve the column names
$clmnNmes = DB::getSchemaBuilder()->getColumnListing($curTable->tblNme);
// return the index page
return view('user.show')->with('rcrds',$rcrds)
->with('clmnNmes',$clmnNmes)
->with('tblNme',$curTable->tblNme)
->with('tblId',$curTable);
}
}
You're running into a namespacing issue.
Your controller is in the App\Http\Controllers namespace, so that's where it will look by default. At the top of your controller, adding a use Searchy; line alongside the existing use lines will make it work, or you can preface Searchy with a \ to tell PHP to start at the namespace root.
$rcrds = \Searchy::search(...);
I am getting the records from my database in two different points, using "get" and "find" methods. The problem is that when I am using "get", "first" or "last" the hidden fields aren't displayed (Its ok), but when I am using "find" they are still there.
<?php
//My Plugin in /plugins/Comunica/Files/src/Model/Entity/File.php
namespace Comunica\Files\Model\Entity;
use Cake\ORM\Entity;
class File extends Entity
{
protected $_hidden = ['password'];
protected $_virtual = ['protected'];
protected function _getProtected(){
return empty($this->_properties['protected']) ? false : true;
}
}
The Call Method:
<?php
$this->Files->find()->toArray();
Again. It is right when calling just one record (first, last, call), It's just wrong when trying with method "find". Any one knows how to solve this?
I have found an answer for this problem. The find returns an object that owns the entities of every result, so that you can convert them by using the "findAll" method inside the table's class.
<?php
//My Plugin in /plugins/Comunica/Files/src/Model/Entity/File.php
namespace Comunica\Files\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\Query;//Include this class to manipulate the results
class File extends Entity
{
protected $_hidden = ['password'];
protected $_virtual = ['protected'];
protected function _getProtected(){
return empty($this->_properties['protected']) ? false : true;
}
//New formatation code
public function findAll(Query $query, array $options)
{
return $query->formatResults(function ($results) {
return $results->map(function($row) {
$row['upload_date'] = $this->dateTimeConvert($row['upload_date']);
return $row->toArray();
});
});
}
}
I solved it like this:
My main aim was to exclude hidden fields by default and have a way to explicitly get Entitys including hidden fields if I need them.
ModelsTable.php
public function beforeFind(Event $event, Query $query){
//ATTENTION: if password field is excluded we have to bypass for Auth-Component to work
if(array_key_exists('password',$_REQUEST)){
return $event;
}
$protected = $this->newEntity()->hidden;
$tableSchema = $this->schema();
$fields = $tableSchema->columns();
foreach($fields as $key => $name){
if(in_array($name,$protected)){
unset($fields[$key]);
}
}
$query->select($fields);
return $event;
}
Model.php
protected $_hidden = [
'password',
'otherSecret'
];
protected function _getHidden(){
return $this->_hidden;
}
To receive hidden fields you can simple add ->select('password') to your query, but to make it more nice I added a custom finder
ModelsTable.php
public function findSecrets(Query $query, array $options)
{
$tableSchema = $this->schema();
$fields = $tableSchema->columns();
return $query->select($fields);
}
Now you can build a query like this to receive Entity including hidden fields:
ModelsController.php
$secretModels = $this->Models->find()->find('secrets');
or whatever query you loke, simply add the custom finder
NOTE: is does not work with ->get($id) so you have to use ->findById($id)->find('secrets')->first()
I'm happy to know what you think about this solution or what you would change - feel free to commend :-)
While using Laravel 5.1, I am trying to check every value before it is saved in the database using Eloquent ORM. My logic is, first trim the value, if the value is an empty string "", then to convert it to null instead of just an empty string.
I was advised to create a Trait which will override the setAttribute method for that.
So here is what I have done
I have a new folder "app\Traits" inside of a file called TrimScalarValues.php which contains the following code
<?php
namespace App\Traits;
trait TrimScalarValues
{
public function setAttribute($key, $value)
{
if (is_scalar($value)) {
$value = $this->emptyStringToNull(trim($value));
}
return $this->setAttribute($key, $value);
}
/**
* return null value if the string is empty otherwise it returns what every the value is
*
*/
private function emptyStringToNull($string)
{
//trim every value
$string = trim($string);
if ($string === ''){
return null;
}
return $string;
}
}
Finally I have a app\Models\Account.php file which contains the following code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;
class Account extends Model
{
use RecordSignature, TrimScalarValues;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'accounts';
protected $primaryKey = 'account_id';
const CREATED_AT = 'created_on';
const UPDATED_AT = 'modified_on';
const REMOVED_AT = 'purged_on';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
//protected $hidden = ['account_id', 'remember_token'];
protected $guarded = ['account_id'];
/**
* Get the industry record associated with the account.
*/
public function industry()
{
return $this->hasOne(industry, industry::primaryKey);
}
public function pk(){
return $this->primaryKey;
}
}
But every time I update a value, I get a white page with no error or logs.
When I modify the app\Models\Account.php and change use RecordSignature, TrimScalarValues; to use RecordSignature; then I do not get a white page but obviously the values are not trimmed and converted to null.
What am I doing wrong here?
You can't call $this->setAttribute() in your trait. Instead you want to call the "original" setAttribute method by using parent:::
public function setAttribute($key, $value)
{
if (is_scalar($value)) {
$value = $this->emptyStringToNull(trim($value));
}
return parent::setAttribute($key, $value);
}
Regarding the empty logs, have you checked the webserver log besides the one from the framework?
I had the same problem and solved it by creating a middleware that filters empty input fields.
public function handle($request, Closure $next) {
$input = $request->all();
if ($input) {
array_walk_recursive($input, function (&$item) {
$item = trim($item);
$item = ($item == "") ? null : $item;
});
$request->merge($input);
}
return $next($request);
}
Don't forget to add your custom middleware to Http/Kernel.php
Found this at Laracasts
You might wanna take a look at this package:
https://packagist.org/packages/iatstuti/laravel-nullable-fields
"This create a trait and allows you to easily flag attributes that should be set as null when being persisted to the database."
I know this post is old, and at that time this package maybe didn't exist yet.
You can use mutator in you model.
For the field account_name mutator should looks like this:
public function setAccountNameAttribute($account_name)
{
if(is_null($account_name))
{
$this->attributes['account_name'] = null;
}
else
{
$this->attributes['account_name'] = $account_name;
}
}
And everytime when you will update or insert the record using Eloquent, account_name will be passed through this mutator.
I am trying to get distinct city names from a MySQL table called "city".
Here is how the controller code looks like:
public function getCityNames()
{
if(Auth::check())
{
$cities = DB::table('city')->distinct()->get();
var_dump($cities);
}
else
{
return Redirect::route('account-signin');
}
}
Here is the code for the model City:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class City extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'city';
/**
* Using a different primary key name
*
*/
protected $primaryKey = 'geoname_id';
public $timestamps = false;
}
The Problem
I can output distinct values from other models using the exact code as in this controller above but when I run it for the city, I get a BLANK page.
I am using Laravel 4 with detailed error messages enabled.
Of course, there is data in the 'city' table
UPDATE:
When I write the following, I get data:
public function Test()
{
return City::where('country_name', '=', 'Canada')->get();
}
But when I write the following, I get the black page? Something with the data size?
public function Test()
{
return City::all()->get();
}
Not sure if this is problem, but are you trying to view the output of var_dump($cities)?
If so, shouldn't return var_dump($cities); give you the output, rather than the empty page?
Code looks like this:
public function getCityNames()
{
if(Auth::check()) // Tip: You can apply auth filters to controllers if you want.
{
$cities = DB::table('city')->distinct()->get();
return var_dump($cities); // Add return here.
}
else
{
return Redirect::route('account-signin');
}
// If the code doesn't go anywhere, it goes here.
return "TEST";
}
I am able to access the city table fine when I ran small queries (see my update in the question). Only explanation could be that I was exceeding the browser buffer size when I was trying to get all . This table has more than 70,000 rows.
I am working on creating models for a module I'm developing but I've run into a problem echoing out the result from a query.
What I get when using a var_dump() calling the the model in the block is NULL
I don't understand because in the resource model, if i do an echo $select it prints out the query which I enter into phpMyAdmin and it find the row. I think i must be trying to output the row wrongly.
This is my resource model:
class MyCompany_Facebook_Model_Resource_Facebookcoupon extends Mage_Core_Model_Resource_Db_Abstract
{
protected function _construct()
{
$this->_init('facebook/facebookcoupon', 'entity_id');
}
public function loadByField($field,$value)
{
$table = $this->getTable('facebook/facebookcoupon');
$where = $this->_getReadAdapter()->quoteInto("$field = ?", $value);
$select = $this->_getReadAdapter()->select()->from($table,array('facebook_id'))->where($where);
$id = $this->_getReadAdapter()->fetchOne($select);
return $id;
}
This is my model
class MyCompany_Facebook_Model_Facebookcoupon extends Mage_Core_Model_Abstract
{
protected function _construct()
{
parent::_construct();
$this->_init('facebook/facebookcoupon');
}
public function loadByField($field,$value)
{
$id = $this->getResource()->loadByField($field,$value);
$this->load($id);
}
}
and i call it using this block
class MyCompany_Facebook_Block_Content extends Mage_Core_Block_Template
{
private $couponCode;
public function displayCoupon($test)
{
$facebookid = Mage::getModel('facebook/facebookcoupon')->loadByField('facebook_id', '14547854');
var_dump($facebookid);
Adrock.use the below for more suitable solution
$model = Mage::getModel('facebook/facebookcoupon') ->getCollection()
->addFieldToFilter('facebook_id', 14547854) ->getFirstItem();
// here you'll get a collection but single record -
Please note:
loadByField($field,$value) in resource model is wrong.you can use load()
function only whenever,you will be trying to fetch data using primary key.