I have entity User with field roles:
/**
* #ORM\Column(name="roles", type="json")
*/
private $roles = [];
public function getRoles(): array
{
return $roles = $this->roles;
}
public function setRoles($roles): self
{
$this->roles[] = $roles;
return $this;
}
I want to add functionality to update user role from ROLE_ADMIN to ROLE_USER. I tried this in my controller but instead of replacing ROLE_ADMIN with ROLE_USER it inerts this: "ROLE_ADMIN""ROLE_USER". This is my controller:
public function updateuser(Request $request, $id) {
$entityManager = $this->getDoctrine()->getManager();
$usr = $this->getDoctrine()->getRepository(User::class)->find($id);
$usr->setRoles("ROLE_USER");
$entityManager->persist($usr);
$entityManager->flush();
First of all its best practice that every users has at least a default role like ROLE_USER. If you want to give users extra roles then you add them with beside ROLE_USER, like for example ROLE_ADMIN.
Now take a close look how arrays work in PHP. Let's take the code of you setter function setRoles.
When you write the value assignment like this $this->roles[] = $roles, then a value is added to the array . Thats why you in you code you have both roles inside you array now. The already existing ROLE_ADMIN and after the function call you added ROLE_USER.
When you write the value assignment like this $this->roles = $roles, then the whole array is overwritten with the new value.
Conclusion:
Thats how you code should look like if you want a simple solution:
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
Then you can call it like this:
$user->setRoles(['ROLE_USER']);
The setRoles function only accepts array.
So your code should change accordingly:
$usr->setRoles(["ROLE_USER"]);
Furthermore, if you want to store it as json, you can use json_encode:
$usr->setRoles(json_encode(["ROLE_USER"]));
Related
Hi I followed a tutorial to implement a friend system. It all works find, but I need to post other columns to the row that just the id's. How would I expand that.
This is the method that is accessed when the add friend button is clicked
public function getAdd($id){
$user = User::where('id', $id)->first();
//After passing all checks. Add other account
Auth::user()->addFriend($user);
echo "Sent";
}
AddTenancy Method
public function addFriend(User $user){
$this->friendsOf()->attach($user->id);
}
I assume the relationship is many-to-many between users. And you need to add additional data to the pivot.
Here's how you'd do that:
public function addFriend(User $user){
$this->friendsOf()->attach($user->id, ['another_col' => 'some data']);
}
Replace 'another_col' and some data with your column and your data. You can also add more than 1 column into the array.
I Have three tables
#1 Table timeline which is my reference table with an Auto incremented ID which is stored in column id
#2 timeline_videos
#3 timeline_else
What happens is on post if a video is uploaded with the post
it will go into Table #2 ,anything else goes into Table #3.
#2-3 have the Auto Increment Id from the Table timeline stored in a column pid
On query of The Timeline I need to join both tables data using id=pid
so I can use the rest of the Relational Data with the post.
I have done a bit of research and can't seem to find a method for doing so.
So far the code I have
Controller
$groupposts = timeline::where([
['owner','=',$owner],['id','<',$lastid],
])
->join('timeline_videos','timeline.id','=','timeline_videos.pid')
//->join('timeline_else','timeline.id','=','timeline_else.pid')
->orderBy('id','desc')
->limit(5)
->get();
This works with no errors with the second Join commented out but I need to also grab the timeline_else data .
Update --
I have now decided to use Eloquent Relationships to join the tables,
my question now is what type of relationship do I have between the
tables?
I realize it basically needs to be able to switch between two tables to
grab data based on the fact that timeline_videos and timeline_else will not be "JOIN" but separated by type .
The tables need to Join with table #1 timeline based on a column I now have named type for clarifying where to look and matching/joining using the id = pid
You can use relationships.
it sounds like timelines has many videos and has many video failures
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
you would have a model for each table and set up the relationships
timelines model:
public function videos()
{
return $this-> hasMany('App\Videos');
}
public function videoFailures()
{
return $this-> hasMany('App\videoFailures');
}
videos model:
public function timeline()
{
return $this->belongsTo('App\Timelines');
}
videos failures model:
public function timeline()
{
return $this->belongsTo('App\Timelines');
}
You can then go:
$timeLine = Timmeline::find($id);
to find videos of the time lines you would do:
$videos = $timeLine->videos();
to find else:
$videoElse = $timeLine-> videoFailures();
By using some of what Parker Dell supplied and a bit more trial and error
My Models Looks like
timeline
class timeline extends Model
{
protected $table ='timeline';
public $timestamps = false;
public function videos()
{
return $this->hasMany('App\timeline_videos','pid','id');
}
public function else()
{
return $this->hasMany('App\timeline_ect','pid','id');
}
}
timeline_ect.php ,I changed the name of the table
class timeline_ect extends Model
{
protected $table='timeline_ect';
public $timestamps = false;
public function timeline()
{
return $this->belongsTo('App\Models\timeline','pid','id');
}
}
timeline_videos
class timeline_videos extends Model
{
protected $table='timeline_videos';
public $timestamps = false;
public function timeline()
{
return $this->belongsTo('App\timeline','id','pid');
}
}
Then Lastly my Controller
$timeline = timeline::with('videos','else')
->orderBy('id','desc')
->limit(5)
->get();
So far no Problem query is correct.
I want to delete multiple records at one time using checkboxes. My code is not working.
my html
#foreach($userallergens as $aller)
<input type="hidden" name="ua_id" value="{{$aller->ua_id}}">
<input type="checkbox" class="allergies" name="allergen[]" value="{{$aller->ua_id}}">
{{ $aller->allergen_name}}</label>
<label>Tolerance Level:<b>{{$aller->tolerance_level}}</b></label><br>
#endforeach
my controller
public function destroy(Request $request){
$id=Auth::user()->id;
$uaid=UserAllergen::where('ua_id', $request['ua_id'])->get();
if (is_array($id))
{
UserAllergen::destroy($uaid);
}
else
{
UserAllergen::where('ua_id', $uaid)->delete();
}
return redirect()->route('user.profile', compact('user', 'id'));
}
ua_id should be ua_id[] so the form posts it as an array, you got it right for the allergens
There are a few mistakes first:
$id=Auth::user()->id;
and
if (is_array($id))
That's never going to work since the user id is always a non array value
Then you need to make a few changes to your code
Also change this
UserAllergen::where('ua_id', $uaid)->delete();
To this
UserAllergen::whereIn('ua_id', $uaid)->delete();
Also unless ua_id is your primary key i would avoid using destroy as it bases on the table primary key (id usually), you can instead use
UserAllergen::where('ua_id', $uaid)->delete();
However, if it's the PK of your table you can use destroy in the case of the array as well reducing your code to just
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::destroy($uaid);
return redirect()->route('user.profile', compact('user', 'id'));
}
or
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::whereIn('ua_id', $uaid)->delete();
return redirect()->route('user.profile', compact('user', 'id'));
}
Delete multiple Rows (record) in Laravel 5.8:
$rowIds = "1,3,5";
$Rowsdeleted = explode(",", $rowIds);
foreach($Rowsdeleted as $rowId) {
$response = YourModelName::where('id',"=",$rowId)->delete();
}
use in controller
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::whereIn('ua_id', $uaid)->delete();
return redirect()->route('user.profile', compact('user', 'id'));
}
when you comes with array of that id's
I want the default value for my Server model's sid to be the uniqid() function to be run every time. Something like this, for example
$table->string('sid')->default(uniqid);
How can I achieve this result?
You can use an event listener to set the sid attribute on your model. You can do this using an event listener, model observer, or just a closure function inside your model's boot function.
// app\Models\YourModel.php
/**
* Define model event callbacks.
*
* #return void
*/
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->sid = uniqid();
});
}
Unfortunately no, MySQL requires constants for the default. So, the default value must be a constant, it cannot be a function or an expression.
Only way is to allow the fields nullable and add uniqid() while creating records on the database like this:
$table->string('sid')->nullable();
Now, When you add records set sid value to uinqid() value
If you have model named Table then
$record = new Table();
$record-> -----
--------
--------
$record->sid = uniqid();
$record->save();
This is the way you can achieve.
UPDATE
You can set default value in model as well like this:
protected $attributes = array(
'sid' => uniqid(),
);
Hope you understand.
i think this is the easiest way
$table->unique('sid')->index()
I have an API that grabs data from a table, serialises the data and then sends back via the service. The code is written using CakePHP using MySQL.
When I pass in the table name (such as RX_Scaled), an error is being returned that the table r_x_scaled can't be found (which don't surprise me, the table name in the database is rx_scaled).
My Model/Table for rx_scaled is defined like this
class rx_scaleds extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('rx_scaled');
}
With the Model/Entity
class rx_scaled extends Entity
{
}
My service API is set like this within the APIController.php file
public function getData($tablename, $id="", $filter = "-", $order = "-", $take = 0)
{
$the_table = $tablename;
$this->autoRender = false;
$table = TableRegistry::get($tablename);
$data = null;
switch (strtolower($the_table))
{
case "rx_scaled":
$data = $table->find();
echo $data;
break;
}
(this is truncated)
The odd thing is that this error does not occur in all tables.
I'm obviously not doing something correctly, but I'm not sure what
You named your table object rx_scaleds but then you pass RX_Scaled to the getData action
cake try not finding a Table Object named RX_Scaled try to inflect the name of the mysql table: so using cake's conventions RX_Scaled is mapped to r_x_scaled
So what can you do?
Use cake conventions
Name you table RxScaledsTable
class RxScaledsTable extends Table
Name you entity RxScaled
class RxScaled extends Entity
and pass the string 'RxScaled' to your action