I want to retrieve all the users and associated roles to the one table in laravel. but i couldn't continue because i'm getting error called
This is my controller function
public function index(){
if(Auth::user()->isAdmin==1){
$users = User::with('roles')->get();
return view('users', campact($users));
} else {
abort(403, 'Unauthorized action.');
}
}
This is my User Model's roles function
public function roles()
{
return $this->belongsToMany(Role::class, 'role_users');
}
This is my Role Class's Users function
public function users()
{
return $this->belongsToMany(User::class,'role_users');
}
This is my data table
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<select class="form-control" data-id="{{$user->id}}" id="role" name="role">
<option value="0">Select a Role</option>
#foreach ($users->roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
</select>
</div>
</form>
</td>
<td>{{ $user->created_at }}</td>
<td>{{ $user->updated_at }}</td>
<td><div class="form-group">
<form method="post" id="userActivate">
{{ csrf_field() }}
<label>
<input type="checkbox" class="flat-red isActive" data-id="{{$user->id}}" #if ($user->isActive) checked #endif>
</label>
</form>
</div>
</td>
<td>
<form id="userDelete" method="post" >
{{ csrf_field() }}
<button type="button" id="delete" data-id="{{$user->id}}" class="btn btn-block btn-danger btn-flat">Delete</button>
</form>
</td>
</tr>
#endforeach
Please help me to solve this.
Change your Controller code
public function index(){
$users = User::with('roles') // Eager loading
->get();
return view('users')->with('users', $users);
}
Then, change your blade code from
#foreach ($users->roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
to
#if(count($user->roles) > 0)
#foreach ($user->roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
#endif
Edit this line:
return view('users', campact($users));
to:
return view('users', compact('users'));
Related
Hi can somebody please guide me how to implement inline table edit with select2 in laravel livewire?
I am having problem in my select as I can change the selected option in my select2 but the value I am getting upon submitting the form is the same as the original value.
Please see code below.
Table
#foreach ($purchaserequestitems as $index => $purchaserequestitem)
<tr >
<td><label class='label label-primary'>{{ $loop->iteration }}</label></td>
<td>
#if($editedPRItemsIndex !== $index)
<label>
{{ $purchaserequestitem['item']['name'] }}
</label>
<br/>
<small>
<label>{{ $purchaserequestitem['item']['code'] }}</label>
</small>
#else
<select wire:model.defer="purchaserequestitems.{{ $index }}.item_id" data-index="{{ $index }}" wire:change="getUomByItemId" class="form-control select2 item">
<option value="">-- Please Select -- </option>
#foreach ($items as $item)
<option value="{{ $item->id }}" >{{ $item->name }}</option>
#endforeach
</select>
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['quantity'] }}
#else
<input type="text" wire:model.defer="purchaserequestitems.{{ $index }}.quantity" class="form-control">
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['itemuomconversion']['unitmeasure']['code'] }}
#else
<select wire:model.defer="purchaserequestitems.{{ $index }}.item_uom_conversion_id" id="edituom" class="form-control select2">
<option value="">-- Please Select -- </option>
#foreach ($uom_options as $uom_option)
<option value="{{ $uom_option->id }}">{{ $uom_option->unitmeasure->code }}</option>
#endforeach
</select>
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['comment'] }}
#else
<textarea wire:model.defer="purchaserequestitems.{{ $index }}.comment" class="form-control"></textarea>
#endif
</td>
<td>
<span class='pull-right'>
#if ($editedPRItemsIndex !== $index)
<button
class='btn btn-primary btn-sm rounded-0 py-0'
wire:click.prevent="editPRItem({{ $index }})">
Edit
</button>
<button
wire:click="deleteConfirm({{ $purchaserequestitem['id'] }})"
class='btn btn-danger btn-sm rounded-0 py-0'>
Delete
</button>
#else
<button wire:click.prevent="update({{ $index }})" class="btn btn-primary">Update</button>
#endif
</span>
</td>
</tr>
#endforeach
JS that sets the value of the select
$('.item').on('change', function (e) {
let data = $(this).val();
let idx = $(this).data('index');
#this.set(`purchaserequestitems.${idx}.item_id`, data);
});
Function that updates the data
public function update($prItemIndex)
{
$pritem = $this->purchaserequestitems[$prItemIndex] ?? NULL;
if(!is_null($pritem)){
$editedItem = PurchaseRequestItem::find($pritem['id']);
if($editedItem){
// dd($pritem);
$editedItem->update([
'item_id' => $pritem['item_id'],
'comment' => $pritem['comment'],
'quantity' => $pritem['quantity'],
'item_uom_conversion_id' => $pritem['item_uom_conversion_id']
]);
}
}
$this->editedPRItemsIndex = null;
}
Any help would be appreciated, or if you guys have any other way to implement an inline table editing with a select2 in it. Thank you
Tried to put the js inside an eventlistener but everytime I change the an option on the select box, it will just return to its original value.
artworkcontroller:
$leads = Artworkrequest::join('artworks', 'artwork_id', '=', 'artworks.id')->where('artworks.user_id', auth()->user()->id)->get();
What I want to do is delete the Artworkrequest by passing the {{$lead->id}} but the problem is that it is selecting the id of the table artworks instead of the id of artworkrequest. How can I pass the id of artworkrequest in my blade?
leads.blade.php:
#foreach($leads as $lead)
<tr>
<td>
<img src="{{ asset('uploads/artworks') }}/{{$lead->picture }}" width="100px" style="width: 100px" alt="">
</td>
<td>{{ $lead->title }}</td>
<td>
<button class="btn btn-dark">bekijk contactgegevens</button>
</td>
<td>
<button class="btn btn-success">Delete</button>
</td>
<td>
<form action="{{ route('lead.delete') }}" method="POST">
#csrf
<input type="hidden" name="id" value="{{$lead->id}}">
<button type="submit" class="btn btn-danger">delete</button>
</form>
</td>
</tr>
#endforeach
For this example, why don't you use Eloquent Relation instead of join?
To Do eloquent relationship you have to define the relationships in respective model.
Artwork.php
class Artwork extends Model
{
public function artworkRequest()
{
return $this->hasMany(ArworkRequest::class);
}
}
ArtworkRequest.php
class ArtworkRequest extends Model
{
public function artwork()
{
return $this->belongsTo(ArworkRequest::class);
}
}
Then in ArtworkController.php you can get the data this way. You don't have to include the with('artwork') if you don't need artwork data too.
$leads = ArtworkRequest::with('artwork')->whereHas('artwork', function($q) {
$q->where('user_id', auth()->user()->id);
})->get();
Then in blade file you can call it with
#foreach($leads as $lead)
{{ $lead->id }}
// additionally, you can also call Artwork data by using
{{ $lead->artwork->name }}
#endforeach
Controller:
public function lead()
{
$user = auth()->user()->id;
$leads = Artworkrequest::with('artwork', 'profile')->get();
return view('artworks.leads', compact('leads'));
}
and blade.php:
#foreach($leads as $lead)
#if(Auth::user()->id == $lead->artwork->user_id )
<tr>
{{$lead->artwork->user_id }}
{{ $lead->id }}
{{ $lead->artwork_id }}
{{ $lead->user_id }}
<td>
{{ $lead->artwork->title }}
</td>
<td>
{{ $lead->profile->first_name }}
</td>
<td>
</td>
<td>
<form action="{{ route('lead.delete') }}" method="POST">
#csrf
<input type="hidden" name="id" value="{{$lead->id}}">
<button type="submit" class="btn btn-danger">delete</button>
</form>
</td>
</tr>
#endif
#endforeach
I am creating a blog in Laravel. I have two tables - posts and categories.
When i want to edit one post, i have a problem with categories. My post controller is sending categories to the view, i can see them while editing, but i don't know how to set the current category in the select option.
The tables are conected:
public function posts(){
return $this->hasMany('App\Post');
}
public function category(){
return $this->belongsTo('App\Category');
}
Controller:
public function edit(Post $post)
{
$categories = Category::all();
return view('admin.posts.edit', compact('post'))->withCategories($categories);
}
View:
<form action="{{ route('posts.update', ["post" => $post->id]) }}" method="post" enctype="multipart/form-data" class="form-horizontal">
#csrf
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Naslov</label>
<div class="col-md-4">
<input type="text" name='title' value='{{ old("title", $post->title) }}' class="form-control">
#if($errors->has('title'))
<div class='text text-danger'>
{{ $errors->first('title') }}
</div>
#endif
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Kategorija</label>
<div class="col-md-4">
<select class="form-control" name="category_id">
#if(count($categories) > 0)
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
#endif
</select>
#if($errors->has('category_id'))
<div class='text text-danger'>
{{ $errors->first('category_id') }}
</div>
#endif
</div>
</div>
How can i make the category display the current category of the selected post in the option select like i have for title? value='{{ old("title", $post->title) }}'
To show the currently associated Category, you can set a default "selected" option based on the $post->category_id:
<option value="{{ $category->id }}" {{ old('category_id', $post->category_id) == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
This a simple ternary that sets the selected attribute of one of the options based on the old() value, or, if old() is not set, then based on the value of $post->category_id
What you are looking for is the selected property of the <option> element.
#forelse ($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == old('category_id', $post->category_id) ? 'selected' : '' }}>
{{ $category->name }}
</option>
#endforelse
A minor change as well in the in you blade template to make use of the #forelse directive for less code.
You could also change your controller code a bit:
return view('admin.posts.edit', compact('post', 'categories'));
Further the laravelcollective/html package might help you a lot in creating forms.
Here I'm trying to loop supplier names using a foreach loop but I'm getting following error
<tbody style="font-size:small">
#foreach($material as $material)
<tr class="odd" role="row">
{!! Form::open(['route'=>'materialsupplier.store','class'=>'form-horizontal p-t-20']) !!}
<td>{{ $material->name }}<input type="hidden" value="{{ $material->id }}" name="mat_id"></td>
<td></td>
<td>
<div class="form-group{{ $errors->has('sup_id') ? ' has-error' : '' }}">
<div >
<select class="form-control js-cities" name="sup_id">
<option value="" selected disabled>Select Supplier</option>
#foreach ($supplier as $supplier)
<option value="{{ $supplier->id}}">{{$supplier->company_name}}</option>
#endforeach
</select>
</div>
</div>
</td>
<td>
{{ Form::submit('Save',['class'=>'far fa-trash-alt btn btn-info btn-sm btn-rounded m-b-1 m-l-5']) }}
</td>
{!! Form::close() !!}
</tr>
#endforeach
</tbody>
after that i chaged my code like this
<select class="form-control js-cities" name="sup_id">
<option value="" selected disabled>Select Supplier</option>
#foreach ($supplier as $supplier)
<option value="{{ $supplier}}">{{$supplier}}</option>
#endforeach
</select>
output
controller
public function index()
{
$material = Material::all();
$supplier = Supplier::all();
return view('materialMgmt.material_suppliyer.create')->withMaterial($material)->withSupplier($supplier);
}
How can I avoid getting this error?
I changed the code as following and its worked
<select class="form-control js-cities" name="sup_id">
<option value="" selected disabled>Select Supplier</option>
#foreach ($supplier as $sup)
<option value="{{ $sup->id}}">{{$sup->company_name}}</option>
#endforeach
</select>
Sir FatemehNB, Thank for your suggestion.
View:
{{ Form::open(array('url'=>'agents/searchStaff',
'class'=>'form-search',
'role'=>'form')) }}
<select class="form-control">
#foreach ($company->users as $user)
<option id="{{ $user->id }}" name="agent">
{{ $user->firstname }} {{ $user->surname }}
</option>
#endforeach
</select>
{{ Form::close() }}
Route:
Route::post('agents/searchStaff', 'AgentsController#postSearchStaff');
Controller:
public function postSearchStaff()
{
$agent_id = Input::get('agent');
dd($agent_id); // For testing purposes - Always returns NULL.
}
I'm unsure as to why the option value's ID isn't being passed onto the controller. Any help and guidance would be appreciated.
You need to change id={{ $user->id }} to value={{ $user->id }},
but this:
<select class="form-control">
#foreach ($company->users as $user)
<option id="{{ $user->id }}" name="agent">
{{ $user->firstname }} {{ $user->surname }}
</option>
#endforeach
</select>
can be done in one line with a bit sugar in your model:
// view
{{ Form::select('agent', $users, $selectedAgentId, $attributes) }}
// User model
public function getFullnameAttribute()
{
return $this->attributes['firstname'].' '.$this->attributes['surname'];
}
// controller:
$users = $company->users->lists('fullname','id'); // Collection method
Change
<select class="form-control">
#foreach ($company->users as $user)
<option id="{{ $user->id }}" name="agent">
{{ $user->firstname }} {{ $user->surname }}
</option>
#endforeach
</select>
to
<select class="form-control" name="agent">
#foreach ($company->users as $user)
<option value="{{ $user->id }}">
{{ $user->firstname }} {{ $user->surname }}
</option>
#endforeach
</select>