How could I clean up this livewire component? - laravel

The code:
<div>
<select name="tags[]" id="tags" multiple
class="select2 mt-1 w-full block rounded-md bg-gray-100 border-transparent hover:border-gray-500 hover:bg-white hover:ring-0">
#if (old('tags'))
#foreach (old('tags') as $oldtag)
<option value="{{ $oldtag }}" selected>{{ $oldtag }}</option>
#endforeach
#else
#isset($post)
#if ($post->tags()->count() > 0)
#foreach ($post->tags as $singleTag)
<option value="{{ $singleTag->text }}" selected>{{ $singleTag->text }}</option>
#endforeach
#endif
#endisset
#endif
</select>
#if ($errors->has('tags'))
<small class="text-red-600">{{ $errors->first('tags') }}</small>
#endif
</div>
**select2 script init below inside #push('scripts')**
It is a livewire component that takes in an optional parameter named $post.
The reason I have else-isset-if is because, if you "edit" a post, the $post parameter gets that post object but if you "create" a new post, there's no post object to load up in the component. That way laravel still tries to read $post->tags()->count() which will throw an error stating "null" has no method called tags().
That's why I've added the isset part.
It works but also looks extremely ugly. I have absolutely no idea what to do with it.

You might consider migrating your conditional logic into a Livewire computed property instead:
public function getTagOptionsProperty() {
$old = request()->old('tags');
return $old ?? $this->post->tags()->pluck('text')->toArray();
}
Then, inside of your Blade view:
#foreach($this->tagOptions)
{{-- ... --}}
#endforeach
Your markup seems to be mixing Blade attributes with Livewire properties, so I'm not entirely sure what's going on here, but there would seem to be a good opportunity for refactoring.

Related

need help logic if and loop laravel

I'm planning to do code confirmation in a program where it requires 2 or more codes and confirmation.I tried and stuck with code like this
#foreach ($kode as $k)
#if ($k->kode != $k->konfirmasi )
<form action="/tps/kode" method="post">
#csrf
<input type="text" name="{{ $k->status }}" id="{{ $k->status }}" placeholder="{{ $k->status }}">
<button type="submit">submit</button>
</form>
{{-- #break --}}
#else
succes
#endif
#endforeach
I tried to use break and continue but that's not the place, maybe. It seems more to the logic where if the konfirmasi is the same and everything is the same then it will be successful. but I'm confused what to use
If I understand your question correctly, then you should first validate the codes and after iterating over the $kode variable, check if a kode was not the same as the konfirmasi. If so, show the form.
#php($failure = false)
#foreach ($kode as $k)
#if ($k->kode != $k->konfirmasi )
#php
$failure = true;
$failedKode = $k;
#endphp
#endif
#endforeach
#if($failure)
<form action="/tps/kode" method="post">
#csrf
<input type="text" name="{{ $failedKode->status }}" id="{{ $failedKode->status }}" placeholder="{{ $failedKode->status }}">
<button type="submit">submit</button>
</form>
#endif
Although this is a solution, let me advise you, like #TimLewis mentioned, move this kind of logic to the controller. This logic doesn't belong in views.

create dynamically checkbox in blade

I´m traying to create list of checkbox in my blade with all roles that i have in my DB. I´m doing loop to get all roles and if to check that roles have this user that i´m doing edit:
#foreach($roles as $rol)
#foreach ($selRoles as $role)
#if ($role == $rol->id)
<div class="col-md-4">
<input type="checkbox" name="rol" checked=checked class="form-check-input" value="{{ $rol->id }}" id="{{ $rol->id }}">
{{ $rol->name }}
</div>
#else
<div class="col-md-4">
<input type="checkbox" name="rol" class="form-check-input" value="{{ $rol->id }}" id="{{ $rol->id }}">
{{ $rol->name }}
</div>
#endif
#endforeach
#endforeach
With this code, my problem it´s that all my roles it´s duplicated. In my controller i have this:
public function edit(User $usuario)
{
$roles = Bouncer::role()->orderBy('title', 'DESC')->get();
$selRoles = $usuario->roles->pluck('id')->toArray(); //selRoles it´s roles from user
$usuario->load('roles');
return view('admin.empleados.edit', compact('usuario', 'roles','selRoles'));
}
and retult in blade it´s:
teleoperadora
teleoperadora
teleoperadora
repartidor
repartidor
repartidor
prueba
prueba
prueba
Jefe de equipo
Jefe de equipo
Jefe de equipo
jefa-sala
jefa-sala
jefa-sala
instalador
instalador
for example. I don´t know that i´m doing bad for get this result in my blade. Anybody can help me please?
Thanks for read and help. Sorry for my english
Your roles get duplicated because you are using two foreach loops. Your selected roles are an array, so it should suffice to check if a role->id is in that array:
#foreach($roles as $role)
<div class="col-md-4">
<input type="checkbox" name="rol" #if(in_array($role->id, $selRoles))checked=checked#endif class="form-check-input" value="{{ $role->id }}" id="{{ $role->id }}">
{{ $role->name }}
</div>
#endforeach
The part #if(in_array($role->id, $selRoles))checked=checked#endif will check the checkbox if the role's id is in your array of selected roles.

Store two values from Dropdown Option Laravel 5.7

I am using dropdown and it's option value is $account->code but it shows code and name
so i want to store code in its column and name in another column
here is my blade code :
<div class="form-group col-md-4">
<label>#lang('site.from_account_number')</label>
<select class="form-control select2" style="width: 100%;" name="from_account_number" id="from_account_number">
#foreach ($accounts as $account)
<option value="{{ $account->code }}">
{{ $account->code }} - {{ $account->name }}
</option>
#endforeach
</select>
</div>
and here is my controller code :
$depositaction->from_account_number = $request->get('from_account_number');
$record_from_acc_name = Account::find($request->get('from_account_number'));
$depositaction->from_account_name = $record_from_acc_name->name;
but i get error said :
ErrorException (E_NOTICE) Trying to get property 'name' of non-object
You should query in code. Please check the below code.
$record_from_acc_name = Account::where('code', $request->get('from_account_number'))->first();

laravel entrust how to check a role's permission in blade?

I am using entrust in my laravel project.
In blade file when I edit a role I want to display all the permissions with checkbox.
But I stuck at the thought that I want the checkbox status is checked if the role has the permission.I pass the role and all permissions to blade ,and try
#foreach($permissions as $permission)
<input type="checkbox" value="{{$permission->name}}"
#if($role->hasPermission($permission->name))
checked="checked"
#endif
#endforeach
but it didn't work
I also try convert $role and $permissions to array and pass them to blade and use foreach twice ,it didn't work either.
Is there any way to make it?
You can try this:
#foreach($permissions as $permission)
#foreach($roles as $role)
#if($permission->hasRole($role->name))
<input type="checkbox" checked="checked" name="perms[[]" value="{{ $permission->id }}">
#else
<input type="checkbox" name="perms[]" value="{{ $permission->id }}">
#endif
#endforeach
#endforeach
turns out that $role also can call the hasPermission method
#foreach($permissions as $permission)
<div class="checkbox pull-left" >
<label class="">
<input type="checkbox" name="perms[]" value="{{$permission->id}}"
#if($role->hasPermission($permission->name)) checked #endif>
<p>{{$permission->display_name}}</p>
</label>
</div>
#endforeach

Laravel post submit not working in production but works in local development

I tried searching and messing around myself for several hours w/o success, so here I am.
Here is my simplified controller:
class SettingsController extends Controller
{
protected $emailService;
protected $prospectEmailService;
public function __construct(EmailServiceInterface $emailService, ProspectEmailServiceInterface $prospectEmailService) {
$this->middleware('auth');
$this->emailService = $emailService;
$this->prospectEmailService = $prospectEmailService;
}
public function pEmails(Request $request)
{
if ($request->isMethod('get'))
{
// do something and load a view - get specific view
}
elseif ($request->isMethod('post')
{
// do something and load a post specific view
}
}
}
The problem is when the get view is loaded and I submit a form, the get page gets loaded again as if post is not submitted or working. I did some testing and found out that after submit, code execution did not even enter the elseif block.
In addition,
the code works perfectly find in local dev environment.
Other controllers can do post w/o problem. Other controllers does not inject service obj in __construct.
I looked into log file, and it doesn't contain anything regarding
this. log level set to debug.
Can someone please enlighten me on where I should look???
front end code:
#extends('layouts.content')
#section('title', 'Prospects Email Settings')
#section('content')
<div id='content'>
<h2>Prospects Email Settings</h2>
<div>
<p>Note:</p>
<h4>Current effective settings: </h4>
<p>Schedule start date and time: {{ $currentSetting->start_dt }} </p>
<p>Sending interval: {{ $currentSetting->span }} days</p>
<p>Email sequence: {{ $currentSetting->email_sequence }}</p>
<form action='/settings/prospectsEmails/' method='post'>
{{ csrf_field() }}
<h4>Create new prospects email settings below:</h4>
<label>Schedule starting date and time: </label>
<input type='datetime-local' name='startdt'>
<br><br>
<label>Sending interval (days): </label>
<select name='interval'>
<option value="7">1 week</option>
<option value="14">2 weeks</option>
<option value="21">3 weeks</option>
<option value="28">4 weeks</option>
</select>
<br><br>
<label>Specify email sequence</label>
<br><br>
<div>
#for ($i = 1; $i < 16; $i++)
<label>Email {{$i}}:</label>
<select name="email_{{ $i }}">
<option value="0">---</option>
#foreach ($emails as $email)
<option value="{{ $email->Email_ID }}">{{ $email->Email_ID }}: {{ $email->subject }}</option>
#endforeach
</select>
<br><br>
#endfor
</div>
<label>Schedule the first email right away:</label>
<input type="radio" name="start_schedule" value="yes"> Yes
<input type="radio" name="start_schedule" value="no" checked="checked"> No
<br><br>
<input type="submit" value="Create/update Email Sequence" />
<br><br>
</form>
#if ($method == 'post')
<h3>{{ $msg }}<h3>
#endif
</div>
</div>
#endsection
I am sure now about the reason causing all this.
It has something to do with the use of "/" in routes and uri.
Because of not following a restrict rule of using "/", some of my uri has "/" at the end and some does not. Eventually cause a mess at some places.
Right now, to make it work, my uri always starts with "/" and ending without "/'.

Resources