Delete multiple records (Laravel) - html

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

Related

Symfony 4 - update JSON user roles

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"]));

How to query multiple rows in a column of a table

Below is my controller and when I dd($types_id); I get an array of two ids. Now the problem is when I pass the variable in the where method to pluck the names of the types associated with the ids, it only fetches the name of the first id instead of the two ids. What may I be doing wrong?
/*Get Type List*/
public function getTypeList(Request $request)
{
$types_id = DB::table("vehicles")
->where("condition_id",1)
->pluck("type_id","id")->unique();
//dd($types_id);
$types = DB::table("type_ids")
->where("type_id", $types_id)
->pluck("name");
//dd($types);
return response()->json($types);
}
Problem 1 - You should be using whereIn for the second query.
Problem 2 - Without selecting any column from table and getting all columns for the collection is bad optimization for the fetching operation. You should be using distinct for the query instead of filtering collection by unique method.
public function getTypeList(Request $request)
{
$types_id = DB::table("vehicles")
->where('condition_id',1)
->select("type_id")
->distinct("type_id")->get()
->pluck("type_id");
$types = DB::table("type_ids")
->select('name')
->whereIn("type_id", $types_id)->get()
->pluck("name");
return response()->json($types);
}
Just change where to whereIn
public function getTypeList(Request $request)
{
$types_id = DB::table("vehicles")
->where("condition_id",1)
->pluck("type_id","id")->unique();
//dd($types_id);
$types = DB::table("type_ids")
->whereIn("type_id", $types_id)
->pluck("name");
//dd($types);
return response()->json($types);
}

How can I know if a table column is a foreign key in Laravel through Model?

So as the title says, how can I know if a field of a Model is a foreign key in Laravel ?
Supose I have a FK column called show_type_id and a model named Event and I want to know if there is a function that given the model class or model table and the named field returns true if it is or false if is not.
...
$model = Event:class; // or Event::getTable();
$isFK = isFK('show_type_id', $model);
...
Edit
Thanks to #piscator this is what is worked:
use Illuminate\Support\Facades\Schema;
function isFK(string $table, string $column): bool
{
$fkColumns = Schema::getConnection()
->getDoctrineSchemaManager()
->listTableForeignKeys($table);
$fkColumns = collect($fkColumns);
return $fkColumns->map->getColumns()->flatten()->search($column) !== FALSE;
}
Try this, assuming your table name is "events":
Schema::getConnection()
->getDoctrineSchemaManager()
->listTableForeignKeys('events')
This will return the Doctrine\DBAL\Schema\ForeignKeyConstraint object.
With this data you could write the isFK method like this:
use Illuminate\Support\Facades\Schema;
function isFK(string $table, string $column): bool
{
$fkColumns = Schema::getConnection()
->getDoctrineSchemaManager()
->listTableForeignKeys($table);
return collect($fkColumns)->map(function ($fkColumn) {
return $fkColumn->getColumns();
})->flatten()->contains($column);
}

Laravel 5.6 - eager load depending on value in parent table

Post.php
$fillable = ['id','flag'];
public function tags()
{
return $this->belongsToMany('App\Tags')->withPivot('pivot_flag');
}
public function flaggedTags()
{
return $this->tags()->where('pivot_flag', 1)->get();
}
Tag.php
$fillable = ['id']
public function posts()
{
return $this->belongsToMany('App\Post');
}
Pivot table post_tag columns: post_id,tag_id,pivot_flag
I need to fetch Post with Tags:
$post = Post::select('id','flag')->with('tags')->find($postId);
However, if the flag is set to 1 in Post then I only want tags which have pivot_flag value in pivot table post_tag set to 1
So in that case I'd have following:
$post = Post::select('id','flag')->with('flaggedTags')->find($postId);
How can I do this in single query? I could always do one query to check if the Post is flagged or not and then run the appropriate query for Tags, but that seems wasteful.
Eloquent or raw MySQL queries are welcome.
Thanks!
UPDATE - Alternative solution
Load all tags and then filter the result depending on Post's flag value:
if($post->flag)
{
$tags = $post->tags->filter(funtction($q) {
return $q->pivot->pivot_flag == 1;
});
}
else
{
$tags = $post->tags;
}
This might be faster depending on number of tags. Not really sure, need to test it though. Any feedback about this in comments is welcome.

How to view data using junction table Yii2

I've got three tables
checkoutcounter {id, name}
user {id, username}
checkoutcounter_users { id, checkoutcounter_id, user_id}
I use gii and then add
in checkoutcounter model (I add and joinWith and find()->with but it still doesn't work):
public function getUser_display()
{
return $this->hasMany(User_display::className(), ['id' => 'user_id'])
->viaTable(CheckoutcounterUsers::tableName(), ['checkoutcounter_id' => 'id']
);
}
In checkoutcounter model search:
public function search($params)
{
$query = FinanceSettingsCheckoutcounter::find()->with('user_display');
$query->joinWith('user_display');
}
what should I add in checkoutcounter view to get usernames or user id's? Why when I add in gridview 'attribute'=>'user_display.id' it doesn't display any data?
echo yii\helpers\Json::encode($dataProvidercheckoutcounter);
shows
{"query":{"sql":null,"on":null,"joinWith":[[["user_display"],true,"LEFT JOIN"]],"select":null,"selectOption":null,"distinct":null,"from":null,"groupBy":null,"join":null,"having":null,"union":null,"params":[],"where":null,"limit":null,"offset":null,"orderBy":null,"indexBy":null,"modelClass":"app\\models\\FinanceSettingsCheckoutcounter","with":["user_display"],"asArray":null,"multiple":null,"primaryModel":null,"link":null,"via":null,"inverseOf":null},"key":null,"db":null,"id":null}
Im not sure how you're using your search() function, but you're not using $params.. And its not returning the results..
I belive the query should be like this:
public function search($params)
{
$result = FinanceSettingsCheckoutcounter::find()->with('user_display')->all();
echo yii\helpers\Json::encode($result);
}
if you are using this as part of a Search Model, returning a dataProvider, check out this link
http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/