Facing Problem Insert Session id In my Database - arrays

I create session id randomly in my controller,but i can't store my session id in my database .I got an error Like this Trying to access array offset on value of type null. Thanks
public function addtocart(Request $request){
$cart=New Cart();
$session_id = Session::get('session_id');
if (!isset($session_id)) {
$session_id = str_random(40);
Session::put('session_id', $session_id);
}
$cart->product_id=$request['product_id'];
$cart->product_name=$request['product_name'];
$cart->product_code=$request['product_code'];
$cart->product_color=$request['product_color'];
$cart->price=$request['price'];
$cart->size=$request['size'];
$cart->quantity=$request['quantity'];
$cart-> $request['session_id'];
$cart->save();
return $cart;
}

On line 3 you store the session id in the $session_id variable.
You then call $cart-> $request['session_id'] which tries to access the $request['session_id'] property. I'm not sure if this is valid PHP but I am sure that this property does not exist.
I assume that wat you want to do is:
$cart->session_id = $session_id

Related

unexpected result in a query in laravel

I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});
pluck will return array if you want to get only single value then use value
// will return array
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
//will return string
$articles=DB::table('users')->where('id','2')->value('name');
// output Sonya Bins
here is an example from the documentation:
if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Read more about it here
Hope it helps.
Thanks
pluck() used to return a String before Laravel 5.1, but now it returns an array.
The alternative for that behavior now is value()
Try this:
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->value('name');
return view('products',compact('articles'));
});
I think it's easier to use the Model + find function + value function.
Route::get('products', function () {
$articles = User::find(2)->value('name');
return view('products',compact('articles'));
});
pluck will return the collection.
I think id is your primary key.
You can just get the first record, and call its attribute's name:
DB::table('users')->where('id','2')->first()->name;
or
DB::table('users')->find(2)->name;
First thing is that you used invalid name for what you pass to view - you don't pass articles but user name.
Second thing is that you use get method to get results instead of first (or find) - you probably expect there is only single user with id = 2.
So to sum up you should use:
$userName = DB::table('users')->find(2)->name;
return view('products',compact('userName'));
Of course above code is for case when you are 100% sure there is user with id = 2 in database. If it might happen there won't be such user, you should use construction like this:
$userName = optional(DB::table('users')->find(2))->name;
($userName will be null if there is no such record)
or
$userName = optional(DB::table('users')->find(2))->name ?? 'No user';
in case you want to use custom string.

Laravel 5.4 - Array returning NULL instead of a numeric value

Here's a problem that is bothering me for a while.
I have a service provider to pass data to all views, everytime the sidebar is rendered. like this:
`
public function boot()
{
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
view()->share('commondata', $commondata);
View::composer('sidebar', function ($view) {
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
$view->with('commondata', $commondata);
});
}`
Doing a {{ dd($commondata) }} returns the correct values for the menucase arrays, but NULL for the $userrole
If i declare the same $userrole variable in a controller and call the variable in the view, the received data is correct.
Why is this happening?
Thanks in advance
Can't understand what are you actually trying to do.
If you want get user role as array, you can using pluck method:
$userRole = User::where('id', Auth::id())->pluck('role')->toArray();
But for current user you can just get the role
$userRole = [Auth::user()->role];
UPD: you also can do it in view without any sharing
{{ Auth::user()->role }}
If your user has many roles from a different table, and you have the relationship defined, you could do
$userrole = Auth::user()->roles->pluck('name');
//will return all the roles names in an array
//Replace name by the actual column you want from 'roles' table.

Can not access object in laravel and has "0" indexes when appliying toArray()

I have these tables
clientes
id
nombre_rz
ced_rif
telefono
id_usuario
solicitantes
id
nombre
email
telefono
id_cliente
cliente->hasMany('solicitante')<br>
solicitante->belongsTo('cliente')<br>
^ This is well written in the models, just trying not to make a wall of text.
After Authenticating, when i do
$cliente = Cliente::where('usuario_id','=',Auth::id())->with('solicitante')->get();
dd($cliente);
or
$cliente = Cliente::where('usuario_id','=',Auth::id())->with(array('solicitante' => function($query)
{
$query->where('cliente_id', '=', '35');
}))->get();
dd($cliente);
i get this obect
Object from query
And using toArray() i get this
Array from object
And if access index 0 of that array like
$array = $cliente->toArray(); dd($array['0']);
i get
[Index 0 of array][3]
As far as i can see the queries are correct, and the data i need is there, but i don't know why i can't access the object like
$cliente->id; $cliente->telefono, $cliente->solicitante->nombre, $cliente->solicitante->email
It always throws
Undefined property: Illuminate\Database\Eloquent\Collection::$telefono
Can't Understand this behavior.
You are returning an array of objects, because you asked Laravel for a group. You can either do
foreach ($cliente as $client)
{
echo $client->telefono;
foreach ($client->solicitante as $solicitante)
{
$solicitante->nombre;
}
}
OR you can specify that you only want one result
$cliente = Cliente::where('usuario_id','=',Auth::id())->with('solicitante')->first();
echo $cliente->telefono;
foreach ($client->solicitante as $solicitante)
{
$solicitante->nombre;
}

drupal_write_record doesn't take object

In drupal 6 i used to do something like this:
<?php
/*
* CLASS Example
*/
class example {
var $id = NULL;
var $title;
var $body;
.....
// Save
function save() {
$primary_key = ($this->id == NULL ? NULL : 'id');
if (drupal_write_record('mytabble', $this, $primary_key)) {
return TRUE;
} else {
return FALSE;
}
}
}
?>
This worked quite well. But in Drupal 7, the drupal_write_record only takes an array and no longer the object $this. The new db_merge also only takes an array.
Since i want to save the properties of my object to the database, the above code was very handy and generic for all kinds of classes.
Is there an alternative way to write an object to database, or a method to place objectproperties into a an array?
Any help will be appreciated!
Robert
drupal_write_record does take an object or an array. Guess your problem is caused somewhere else.
drupal_write_record($table, &$record, $primary_keys = array())
$record: An object or array representing the record to write, passed in by reference. If inserting a new record, values not provided in $record will be populated in $record and in the database with the default values from the schema, as well as a single serial (auto-increment) field (if present). If updating an existing record, only provided values are updated in the database, and $record is not modified.
More info on drupal_write_record for D7.

Model won't update

Using cakephp:
I am trying to update customer information and the address the customer is linked to.
such that Customer.address_id = Address.id, and
Customer Model
$belongsTo = 'Address';
From the customers_controller
function profile($id = null)
{
if (empty($this->data['Customer']))
{
$this->Customer->id = $id;
$this->data = $this->Customer->read();
}
else
{
$this->Customer->id = $this->data['Customer']['id'];
$this->Customer->read();
$this->Customer->save($this->data['Customer']);
$this->Customer->Address->save($this->data['Address']);
}
}
Customer correctly updates, but Address always inserts a new row. How do I get this address to update?
first of all, take away lines 11 and 12. those serve no purpose. make sure your view contains form elements for Customer.id and Address.id. If you are just updating the Address you dont need line 13 either. The short answer is that Cakephp will insert row instead of update if the primary key is missing. In your case this means [Address][id].

Resources