Laravel - Trying to get property on a non-object - laravel

I'm attempting to create a simple data display form in Laravel to display contact details given phone number. Phone number is passed in to the form from the URL (route). If the URL is does not include a phone number all the fields of the form should be empty string. To achieve this I just check if the URL is called without a phone number ($number) and if so, create an associative array with the correct keys and empty strings as values
class InboundCallController
{
public function inboundCall($number=null){
if($number==null) {
$contact=array(
"id"=>"",
"registration_no"=>"",
"title"=>"",
"firstname"=>"",
"lastname"=>"",
"primary_contact"=>"",
"secondary_contact"=>"",
"email"=>"",
"gender"=>"",
"address_line1"=>"",
"address_line2"=>"",
"city_state_province"=>"",
"zip"=>"",
"country"=>"");
return view('InboundCall')
->with('number',null)
->with('contact',$contact);
}
$contact=$this->retrieveContact($number);
return view('InboundCall')
->with('number',$number) //CLI passed from soft-phone
->with('contact',$contact) //Contact details retrieved from db
}
private function retrieveContact($number){
return DB::table('contacts') //Retrieve contact
->where('primary_contact',$number)
->first();
}
}
Trying to get property of non-object (View: /var/www/html/csp/resources/views/InboundCall.blade.php)
On line 37 of the blade I have this:
value="{{$contact->primary_contact}}"

That's the idea.. If $number is null then you send an associative array to the view, which is not of type object.. It's an array so you can't access the values via ->.. Try accessing the data like this instead in the view, add # to void promoting error, when $contact is null
value="{{ #$contact['primary_contact'] }}"
EDIT(for others in the same trouble):
You might also want to consider not sending an object if you have $number and an array otherwise.. You might send a new Contact where Contact is the name of the model and maybe initialize the fields of Contact as empty or make a static method Contact::emptyContact that returns an object of type Contact so you don't have to check the type of data inside the view

value="{{$contact->primary_contact}}"
here $contact is an array not object use it like this
value="{{$contact['primary_contact']}}"

Related

Ignore empty form values on update using laravl5

Is there anyway to remove empty form value form request->all() method ?
This is what i am trying to do on update,In other words only post filled form values.
$data = request()->except(['_token','id']);
DB::table($table)->where('id',$id)->update($data);
Note:I have dynamically generated columns so i think i can't use those column in except parameters's list.
This updates all the column of the row,but all i want to update only those column that's value is filled and for the remaining columns/fields keep the same old value
Have a look at array_filter
// All posted data except token and id
$data = request()->except(['_token','id']);
// Remove empty array values from the data
$result = array_filter($data);
// update record
DB::table($table)->where('id', $arr)->update($result);
Hope this helps.
// app/controllers/GiftsController.php
public function update($id)
{
// Grab all the input passed in
$data = Input::all();
// Use Eloquent to grab the gift record that we want to update,
// referenced by the ID passed to the REST endpoint
$gift = Gift::find($id);
// Call fill on the gift and pass in the data
$gift->fill($data);
$gift->save();
}
I found this piece of code in this tutorial and works like charm. I hope it helps.

Laravel 5 - Limiting Eloquent Where Parameters When Using Request Object Data For Get

I have controller functions that look like:
public function get(Request $request){
return json_encode($this->users->get($request->all));
}
where $this->users references a repository for my User model. Inside of this repository, I have a function that looks like:
public function get($request){
return User::where($request)->get()->toArray();
}
I can dynamically pass in any number of parameters to search on through my HTTP request with the above code without having to explicitly state the column names.
This works well as long as all the parameters passed in through the request are valid column names. It will error out if I pass in a parameter that is a not valid table column.
I have the protected $fillable array defined in each of my models corresponding to my repositories.
Is there anyway to enforce what can be passed into the where() method above so that only valid columns defined in the $fillable array in my model are ever passed in?
For example, let's say I have a users table with columns (id, name, description). The GET URL I pass in looks like:
GET /user?name=mike&description=skinny&age=45
There are three parameters in the URL above, but only two of them are valid column names. I would like the age parameter to be automatically taken out. In my current code, the above URL will return an error response since the age column does not exist.
You can use array_only() helper:
return User::where(array_only($request, $this->fillable))->get()->toArray();
It will filter $request and will keep only key/value pairs which are in the $fillable array.
If this code is not in a model, change $this->fillable to appropriate variable or method call.
I wrote a package for doing this kind of filtering for models. It will allow you to filter based on User::filter($request->all())->get(); while defining each possible column's where() constraint.
https://github.com/Tucker-Eric/EloquentFilter
Try doing something like this:
public function get(Request $request)
{
$user = new User();
return User::where(
$request->only($user->getFillable())
)->get()->toArray();
}
By creating an instance of User you can then access it's fillable properties using getFillable(). By passing this list into $request->only(...) you can restrict the values you pull out to only those that are in your fillable array. Hopefully that should mean only fillable values are considered as part of your query.
Hope it helps.

PasswordField validation in SilverStripe

I have a member in my project called Customer. I need to validate PasswordField.
I created a function in my page containing the PasswordField as below
function getValidator() {
$data = $this->loadData();
if (#$data['Password']->minLength(7)) {
return $this->validationError('Password', 'Password field should contain minimum 7 charactors', 'bad');
}
}
This does not give any result. How do I get this working?
Remove that ugly # from your code and watch that beautiful error message. Error supression is a real bad practice, you should avoid that
There is already a class PasswordValidator which is used by the Member object and can check the minimum length of a password. (See API Docs for PasswordValdiator)
If you show us more code I can try to help you implementing it right.
Is your Customer object a subclass of Member? Where is the password changed? What FormField is used for Password? There is also a ConfirmedPasswordField showing two masked fields for matching passwords where you can set a minlength.
So, assuming you save your password in a field called Password you could set up the field e.g.
$passwordField = ConfirmedPasswordField('Password', 'Choose a password');
$passwordField->minLength = 7; //there is no setter method for that right now
Then add $passwordField to your FieldList e.g using
$fields->push($passwordField);

Converting Laravel-4 Eloquent query results to arrays

I'm trying to get my route to insert a new row into the database, and if successful return the record (with its new primary key id) in some JSON. I'm getting the following error:
{
"error":
{
"type":"BadMethodCallException",
"message":"Call to undefined method Illuminate\\Database\\Query\\Builder::to_array()",
"file":"\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php",
"line":1418
}
}
This is my route:
Route::post('/client/create', function()
{
$client = Client::create(Input::all());
if($client)
{
return json_encode(array('Result' => 'OK', 'Record' => $client->to_array()));
}
else
{
return json_encode(array('Result' => 'ERROR', 'Message' => 'Error Inserting Record =('));
}
});
According to the Laravel docs I've read, you're supposed to use ->to_array() to convert your model to an array, and ::create returns an instance of the model if successfully inserted. I've checked the database, and the records are being inserted just fine.
By default if you were to return an Eloquent model directly it would convert the model to it's JSON representation. This is because the __toString magic method on each model returns the model as JSON by using the toJson method.
As such the model implements both the ArrayableInterface and JsonableInterface. That means you can directly call toJson or toArray on a model.
Now you can mark columns as hidden. This means that when a model is converted into it's array or JSON representation some columns are removed (think publicly accessible API, you don't want passwords showing up!). I'm not totally sure but maybe the ID of your model is being hidden.
At the end of the day, all you need to do is return the instance.
return $client;
It'll be converted to JSON for you automatically.
The to_array() method comes from Laravel 3. Use toArray() in Laravel 4.
I see question similar you try to return data to jquery jtable and same me
Player::orderBy($sort)->paginate($pagesize)->getCollection();
return Response::view(array('Result'=>'OK','Records'=>$player->toArray()));
for try many hour I found solution getcollection pull instance from object and then solve

codeigniter alternative to Get variables

I was looking for a way to pass "GET" variables in codeigniter and ended up coming across this :
link text
I am wondering how to implement it.
For example :
www.website.com/query would give me every entry in the DB .
Typically I would have
www.website.com/query/?id=5 to get the equivalent entry.
when i try to do that the CI way :
www.website.com/query/id/5
I get a 404 error since it is looking for a class named id and it can't find it.
is there any way to get a step by step way to do this?
thank you.
Two good ways to achieve this using methods intended by the Codeigniter developers.
OPTION ONE:
If you always expect an "id" parameter to be present you could take advantage of a feature where you pass the value in the URI immediately after the method (function) you want to call.
Example passing /[controller]/[method]/[value]:
http://www.website.com/query/index/5
You would then access the value of "id" as an expected parameter of the function.
Class Query extends Controller {
...
// From your URL I assume you have an index method in the Query controller.
function index($id = NULL)
{
// Show current ID value.
echo "ID is $id";
...
}
...
}
OPTION TWO:
If you would like to allow many parameters to be passed in addition to ID, you could add all parameters as key=>value pairs to the URI segments in any order.
Example passing /[controller]/[method]/[key1]/[val1]/[key2]/[val2]/[key3]/[val3]:
http://www.website.com/query/index/id/5/sort/date/highlight/term
You would then parse all the URI segments from the 3rd segment ("id") forward into an array of key=>value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Query extends Controller {
...
// From your code I assume you are calling an index method in the Query controller.
function index()
{
// Get parameters from URI.
// URI Class is initialized by the system automatically.
$data->params = $this->uri->uri_to_assoc(3);
...
}
...
}
This would give you easy access to all the parameters and they could be in any order in the URI, just like a traditional query string.
$data->params would now contain an array of your URI segments:
Array
(
[id] => 5
[sort] => date
[highlight] => term
)
HYBRID OF ONE AND TWO:
You could also do a hybrid of these where ID is passed as an expected parameter and the other options are passed as key=>value pairs. This is a good option when ID is required and the other parameters are all optional.
Example passing /[controller]/[method]/[id]/[key1]/[val1]/[key2]/[val2]:
http://www.website.com/query/index/5/sort/date/highlight/term
You would then parse all the URI segments from the 4th segment ("sort") forward into an array of key=>value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Query extends Controller {
...
// From your code I assume you are calling an index method in the Query controller.
function index($id = NULL)
{
// Show current ID value.
echo "ID is $id";
// Get parameters from URI.
// URI Class is initialized by the system automatically.
$data->params = $this->uri->uri_to_assoc(4);
...
}
...
}
$id would contain your ID value and $data->params would contain an array of your URI segments:
You can still use GET parameters, they're just mapped to controller member function parameters:
test.com/query/id/4
Would map to the controller:
$query->id($id);
This assumes you have added a query controller and member function properly in the controllers folder in your CI application.
You can also pass your parameter values as POST parameters using a form and the CI input class.
Use $this->uri->uri_to_assoc(2) 2 is an offset, as you starting your associative array of segments in the 2nd segment. You will also need a route to make /query map to a controller and method (unless you do this in the index() method).
So, this URL:
/query/id/foo/key/bar
could be read using:
$get = $this->uri->uri_to_assoc(2);
echo $get['id']; // 'foo'
echo $get['key']; // 'bar'
It's not great, but it works.

Resources