Submit form from a tab content - laravel

I'm new at Laravel. How can I submit form from a tab content and return to the same tab content view? Example, I choose November form then when I submit it return to November. I'm really confusing right now.
This is my controller :
public function project_charter()
{
$nik = Sentinel::getUser()->nik;
$data = AccelerateMentee::select(
'accelerate_mentee.*',
'accelerate_rotation.start_date',
'accelerate_rotation.id as id_rotation',
'accelerate_rotation.status as status_rotation'
)
->leftJoin('accelerate_rotation', 'accelerate_rotation.id', '=', 'accelerate_mentee.rotation')
->where([
['accelerate_mentee.nik', '=', $nik],
])
->first();
if(!empty($data)){
$first_month = date('m', strtotime($data->start_date));
} else {
$first_month = null;
}
$project_activity = AccelerateProjectActivity::where([
['id_rotation', '=', $data->id_rotation],
['month', '=', $first_month]
])->get();
This is my view :
<div class="tab-content mt-3 ">
<ul class="nav nav-pills nav-white" id="pills-tab" role="tablist">
#for($i = 0; $i < 6; $i++)
#php $month = date('m', mktime(0, 0, 0, ($first_month + $i), 1)); #endphp
<li class="nav-item">
<a class="nav-link {{$i == 0 ? 'active' : ''}} get-project-activity" data-month="{{ $month }}" href="{{'#table_'. $month }}" data-toggle="tab">
{{ date('F', mktime(0, 0, 0, ($first_month + $i), 1)) }}
</a>
</li>
#endfor
</ul>
<div class="tab-content" id="pills-tabContent">
#for($i = 0; $i < 6; $i++)
#php $month = date('m', mktime(0, 0, 0, ($first_month + $i), 1)); #endphp
#if($i == 0)
<div class="tab-pane show mt-5 {{$i == 0 ? 'active' : ''}}" id="{{'table_' . $month }}" role="tabpanel">
<div class="card my-2">
<div class="card-body">
<div class="d-flex justify-content-between pb-5">
<h3>Project Activity {{ date('F', mktime(0, 0, 0, ($first_month + $i), 1)) }}</h3>
#if($data->status_rotation == 'draft')
<button class="btn btn-primary btn-sm create-activity" data-month="{{ $month }}">
<i class="fa fa-plus"></i>
Add Project Activity
</button>
#endif
</div>
<div class="mb-5">
#include('pages.accelerate.mentee.element.table_project_activity')
</div>
</div>
</div>
</div>
#else
<div class="tab-pane mt-5" id="{{'table_' . $month}}" role="tabpanel" aria-labelledby="data">
<div class="card my-2">
<div class="card-body">
<div class="d-flex justify-content-between pb-5">
<h3>Project Activity {{ date('F', mktime(0, 0, 0, ($first_month + $i), 1)) }}</h3>
#if($data->status_rotation == 'draft')
<button class="btn btn-primary btn-sm create-activity" data-month="{{ $month }}">
<i class="fa fa-plus"></i>
Add Project Activity
</button>
#endif
</div>
<div class="mb-5" id="{{'detail_' . $month}}">
</div>
</div>
</div>
</div>
#endif
#endfor
</div>
</div>
Hope u guys can help me, I try many ways but didn't work. I'm really really confusing. Thanks!

Related

Getting the sum of two multiplied index of two different dynamic input field - Laravel Livewire

Problem
I want to get the sum of all ingredients and multiply it from the measurement given by the user, these are the list of measurements and their respective values (in number),
-pcs (100)
-mL (1)
-cups (183)
-liter (1000)
-kgs (1000)
-grams (1)
and it must give the automated value
this is a sample input
multiple the first row (in my case 1 * pcs (with the value of 100))
Then after multiplying the rows with the measurements
The Serving - autoCalculate must have the value of ($total / 300);
My Livewire Component
'<?php
namespace App\Http\Livewire;
use App\Models\Recipe;
use Livewire\Component;
class MainIngredient extends Component
{
public $main_ingredientsRecipeName = [];
public $main_ingredientsNumberPortion = [];
public $main_ingredientsRecipeMeasure = [];
public $allRecipes = [];
public $total_numberPortion = 0;
public $sum_numberPortion = 0;
public $total_measurement = 0;
public $sum_measurement = 0;
public $numberPortion;
public function mount()
{
$this->allRecipes = Recipe::all();
$this->main_ingredientsNumberPortion = [
[
'numberPortion' => '',
$this->total_numberPortion += 1,
],
];
$this->main_ingredientsRecipeMeasure = [
[
'measurement' => '',
$this->total_measurement += 1,
],
];
$this->main_ingredientsRecipeName = [
['main_ingredient' => '',]
];
}
public function addMainIngredient()
{
$this->main_ingredientsNumberPortion[] =
[
'numberPortion' => '',
$this->total_numberPortion += 1,
];
$this->main_ingredientsRecipeMeasure[] =
[
'measurement' => '',
$this->total_measurement += 1,
];
$this->main_ingredientsRecipeName[] =
[
'main_ingredient' => '',
];
}
public function removeMainIngredient($index)
{
unset($this->main_ingredientsNumberPortion[$index]);
unset($this->main_ingredientsRecipeMeasure[$index]);
unset($this->main_ingredientsRecipeName[$index]);
$this->main_ingredientsNumberPortion = array_values(
$this->main_ingredientsNumberPortion
);
$this->main_ingredientsRecipeMeasure = array_values(
$this->main_ingredientsRecipeMeasure
);
$this->main_ingredientsRecipeName = array_values(
$this->main_ingredientsRecipeName
);
}
public function render()
{
// dd($this->total_numberPortion);
return view('livewire.main-ingredient');
}
}'
Laravel View
<div style="background-color:#509941;" class="rounded p-3 w-50 m-auto ">
<div style="display: none">
{{ $total = 0 }}
</div>
<h5 style="font-weight: 500" class="text-start text-light py-2">Ingredients with portions:
</h5>
<div class="row d-flex justify-content-between ">
<div class="col-lg-2 my-auto">
#foreach ($main_ingredientsNumberPortion as $index => $numberPortion)
<input class="my-1 form-control " style="border: none; outline:none;"
type="number"
id="numberPortion-checker" name="numberPortion[{{ $index }}]"
wire:model="main_ingredientsNumberPortion.{{ $index }}.numberPortion"
required>
#endforeach
</div>
<div class="col-lg-2 my-auto">
#foreach ($main_ingredientsRecipeMeasure as $index => $measurement)
<select style="color: rgb(17, 80, 17); border: none; outline:none;"
id="measurement-checker"
class="my-1 typeahed py-1 px-1 rounded" name="measurement[{{ $index }}]"
wire:model="main_ingredientsRecipeMeasure.{{ $index }}.measurement"
value="pcs" required>
<option value="pcs">pcs</option>
<option value="mL">mL</option>
<option value="cups">cups</option>
<option value="liter">liter</option>
<option value="kgs">kgs</option>
<option value="grams">grams</option>
</select>
#endforeach
</div>
<div class="col-lg-8 my-auto ">
#foreach ($main_ingredientsRecipeName as $index => $main_ingredient)
<input style="border: none; outline:none;" type="text" name="main_ingredient[{{
$index }}]"
class="my-1 py-1 px-2 rounded" placeholder="Place Ingredients here"
wire:model="main_ingredientsRecipeName.{{ $index }}.main_ingredient" required
/>
<a href="#" wire:click.prevent="removeMainIngredient({{ $index }})">
<button style="background-color: rgba(196, 72, 72, 0.644);" class=" mx-1 btn
btn-sm text-light">
Delete
</button>
</a>
#endforeach
</div>
</div>
<div class="text-start py-2">
<div>
<button style="opacity: 0.6" class=" btn btn-sm btn-light text-black"
wire:click.prevent="addMainIngredient">
Add Ingredient
</button>
</div>
<br>
{{-- CAN GET SUM AND DIVIDE BUT IT MUST RETURN WITH MEASUREMENT --}}
#foreach ($main_ingredientsNumberPortion as $index => $num)
#if (($measurement[$index] ?? 0) == 'mL')
{{-- IF MEASUREMENT IS ML --}}
{{ $total += (int) $num['numberPortion'] * 1 }}
#elseif (($measurement[$index] ?? 0) == 'cups')
{{-- IF MEASUREMENT IS CUPS --}}
{{ $total += (int) $num['numberPortion'] * 183 }}
#elseif (($measurement[$index] ?? 0) == 'liter')
{{-- IF MEASUREMENT IS LITER --}}
{{ $total += (int) $num['numberPortion'] * 1000 }}
#elseif (($measurement[$index] ?? 0) == 'kgs')
{{-- IF MEASUREMENT IS KGS --}}
{{ $total += (int) $num['numberPortion'] * 1000 }}
#elseif (($measurement[$index] ?? 0) == 'grams')
{{-- IF MEASUREMENT IS KGS --}}
{{ $total += (int) $num['numberPortion'] * 1 }}
#else
{{-- DEFAULT MEASUREMENT PCS --}}
{{ $total += (int) $num['numberPortion'] * 100 }}
#endif
#endforeach
</div>
<div class="row pt-3">
{{-- <h5 class="">Serving:</h5> --}}
<div class="">
<label for="serving" class="text-light">Serving - Auto-Calculate:</label>
<br>
<input style="border: 1px green solid; outline:none;" class="typeahead rounded py-1
px-3 w-50"
type="number" name="serving" id="serving" value="{{ $total / 300 }}" />
</div>
</div>
</div>

search in PHP Array, similar to MySQL Like %var% search with livewire

I saw other questions that usually use preg_grep but my problem was not solved
In the LiveWire component, I receive information from the web service and display it in a table.
Now the user does the search and I want to display the items that look like the searched phrase
I wrote the code like this:
class Cryptolist extends Component
{
use WithPagination;
public bool $loadData = false;
protected $paginationTheme = 'bootstrap';
public $perPage = 10;
public $search = '';
public function init()
{
$this->loadData = true;
}
public function getBalance($asset)
{
$this->dispatchBrowserEvent('setPrice' ,[
'asset' => $asset,
'price' => getCryptoBalance($asset)
]);
}
public function setPerPage(int $page)
{
$this->perPage = $page;
}
public function render()
{
try {
if ($this->loadData == true) {
$api = new \Binance\API('','');
$coins = $api->coins();
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , collect(preg_grep('~'.$this->search.'~i', $coins))->paginate($this->perPage));
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
and this is view:
<div class="nk-block" id="loadesh1" >
<div class="card card-bordered card-stretch">
<div class="card-inner-group">
<div class="card-inner position-relative card-tools-toggle">
<div class="card-title-group">
<div class="card-tools mr-n1">
<ul class="btn-toolbar gx-1">
<li>
<a class="btn btn-icon search-toggle toggle-search" data-target="search" href="#"><em class="icon ni ni-search"></em></a>
</li>
<li class="btn-toolbar-sep"></li>
<li>
<div class="toggle-wrap">
<a class="btn btn-icon btn-trigger toggle" data-target="cardTools" href="#"><em class="icon ni ni-menu-right"></em></a>
<div class="toggle-content" data-content="cardTools">
<ul class="btn-toolbar gx-1">
<li class="toggle-close">
<a class="btn btn-icon btn-trigger toggle" data-target="cardTools" href="#"><em class="icon ni ni-arrow-left"></em></a>
</li>
<li>
<div class="dropdown">
<a class="btn btn-trigger btn-icon dropdown-toggle" data-toggle="dropdown" href="#"><em class="icon ni ni-setting"></em></a>
<div class="dropdown-menu dropdown-menu-xs dropdown-menu-right">
<ul class="link-check">
<li><span>show</span></li>
<li #if($perPage === 10) class="active" #endif>
10
</li>
<li #if($perPage === 20) class="active" #endif>
20
</li>
<li #if($perPage === 50) class="active" #endif>
50
</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
</div>
<div class="card-search search-wrap" data-search="search">
<div class="card-body">
<div class="search-content">
<a class="search-back btn btn-icon toggle-search" data-target="search" href="#"><em class="icon ni ni-arrow-left"></em></a><input wire:model="search" class="form-control border-transparent form-focus-none" placeholder="type for search" type="text"><button class="search-submit btn btn-icon"><em class="icon ni ni-search"></em></button>
</div>
</div>
</div>
</div>
<div class="card-inner p-0" wire:init="init">
<div class="nk-tb-list nk-tb-ulist">
<div class="nk-tb-item nk-tb-head">
<div class="nk-tb-col">
<span class="sub-text">name</span>
</div>
<div class="nk-tb-col tb-col-mb">
<span class="sub-text">balance</span>
</div>
</div>
#foreach ($coins as $item => $value)
<div class="nk-tb-item">
<div class="nk-tb-col">
<a href="/demo5/user-details-regular.html">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0" src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid" alt="">
#else
<img style="border-radius: 0" src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png" class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</a>
</div>
<div class="nk-tb-col tb-col-mb">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light" wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
But this error is given. Is my search method correct?
Array to string conversion

Access data in laravel

I need to access data on my view. can you assist me in reviewing my code its throwing me an error massage: "Trying to get property 'avatar' of non-object"
My controller:
$user = User::find($id);
$profile = Personal_Details::select('*')->where('user_id', $id)->first();
//return $profile;
$idd = $user->id;
$name = $user->name;
$email = $user->email;
$avatar = $user->avatar;
$lastname = $profile->lastname;
$cellNumber = $profile->cellNumber;
$street = $profile->address_street;
$city = $profile->address_city;
$province = $profile->address_province;
$postal = $profile->address_postal_code;
$records = array(['id'=>$idd, 'avatar'=>$avatar, 'name'=>$name." ".$lastname,'email'=>$email, 'cellnumber'=>$cellNumber, 'address1'=>$street.", ".$city, 'address2'=>$province.", ".$postal]);
$record = $records[0];
// return $record;
return view('admin.profile.specialist')->with(['record'=>$record]);
My view:
<div class="px-4 pt-0 pb-4 bg-dark">
<div class="media align-items-end profile-header" style="padding-top: 5%">
<div class="profile mr-3"><img src="/storage/avatars/{{ $record->avatar }}" alt="..." width="130" class="rounded mb-2 img-thumbnail">Edit profile</div>
<div class="media-body mb-4 text-white">
<h4 class="mt-0 mb-0">{{ $record->name }}</h4>
<p class="small mb-4">
<i class="fa fa-envelope mr-2"></i>{{ $record->email }}<br>
<i class="fa fa-phone mr-2"></i>{{ $record->cellnumber }}<br>
<i class="fa fa-map-marker mr-2"></i>{{ $record->address1 }},<br> {{ $record->address2 }}<br>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</p>
</div>
<div class="custom-control custom-switch text-white">
<div class="row">
<a hrt="" style="padding-right:43px">Personal</a>
<input type="checkbox" class="custom-control-input" id="customSwitch1">
<label class="custom-control-label" for="customSwitch1">Business</label>
</div>
</div>
</div>
</div>
my response when i uncomment return $record:
{"id":2,"avatar":"default.jpg","name":"Test Data","email":"example#example.io","cellnumber":"0711234567","address1":"1002 Highway, Geelong","address2":"Melbe, 21910"}
I'm not sure what i have missed or maybe the way m trying to access code is wrong.
"Trying to get property 'avatar' of non-object"
This means you're using a variable as an object when it's something else (aray, string, null, etc). This happens in your case because of the following lines
$records = array(['id'=>$idd, 'avatar'=>$avatar, 'name'=>$name." ".$lastname,'email'=>$email, 'cellnumber'=>$cellNumber, 'address1'=>$street.", ".$city, 'address2'=>$province.", ".$postal]);
$record = $records[0];
$record is an array here. $record->avatar will throw the error. $record['avatar'] will access the avatar key of the $record array.
But that is a bit redundant because you've already got all the information you need in the $user and $profile variables. $records and $record have no reason to exist.
$user = User::find($id);
$profile = Personal_Details::select('*')->where('user_id', $id)->first();
return view('admin.profile.specialist', compact('user', 'profile');
$user and $profile are objects so you can use them as such in your view.
<div class="px-4 pt-0 pb-4 bg-dark">
<div class="media align-items-end profile-header" style="padding-top: 5%">
<div class="profile mr-3">
<img src="/storage/avatars/{{ $user->avatar }}" alt="..." width="130" class="rounded mb-2 img-thumbnail">
Edit profile
</div>
<div class="media-body mb-4 text-white">
<h4 class="mt-0 mb-0">{{ $user->name }}</h4>
<p class="small mb-4">
<i class="fa fa-envelope mr-2"></i>{{ $user->email }}<br>
<i class="fa fa-phone mr-2"></i>{{ $profile->cellnumber }}<br>
<i class="fa fa-map-marker mr-2"></i>{{ $profile->address_street}}, {{ $profile->address_city }},<br> {{ $profile->address_province }}, {{ $profile->address_postal_code }}<br>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</p>
</div>
<div class="custom-control custom-switch text-white">
<div class="row">
Personal
<input type="checkbox" class="custom-control-input" id="customSwitch1">
<label class="custom-control-label" for="customSwitch1">Business</label>
</div>
</div>
</div>
</div>
And that's it. The following might not apply to you, so feel free to ignore.
The query Personal_Details::where('user_id', $user->id)->get() suggests a One-to-one relationship.
You could declare it and then use it in your controller/view.
# User model
public function profile()
{
return $this->hasOne(Personal_Detail::class, 'user_id');
}
# Personal_Detail model
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
# Controller
$user = User::with('profile')->find($id);
return view('admin.profile.specialist', compact('user');
And then in your view, you could replace $profile->... by $user->profile->...

How do I get total in a foreach loop

I have a div that displays items , quantities and total prices for each item using a foreach loop. I now want to get the total amount and dont seem to get it.
This is my blade file
<div class="order-summary">
<div class="order-col">
<div><strong>PRODUCT</strong></div>
<div><strong>TOTAL</strong></div>
</div>
<div class="order-products">
#if(session('cart'))
#foreach(session('cart') as $id => $details)
<?php
$total = 0;
$total += $details['price'] * $details['quantity'] ;
$total_amount += $details['price'] * $details['quantity'];
?>
<div class="order-col">
<div>
<h4 class="nomargin">{{$details['quantity'] }}x {{ $details['name'] }}</h4>
</div>
<div>KSh {{ $total }}</div>
</div>
#endforeach
#endif
</div>
<hr>
<div class="order-col">
<div>Shiping</div>
<div><strong>KSh 300</strong></div>
</div>
<hr>
<div class="order-col">
<div><strong>TOTAL</strong></div>
<?php $total_amount += $total?>
<div><strong class="order-total">KSh {{ $total_amount }} </strong></div>
</div>
</div>
I have also tried <div><strong class="order-total">KSh <?php echo $total_amount?> </strong></div> but still does not work.
I get an error of undefined variable total_amount. How do I go about it?
The variables $total and $total_amount must be outside of the foreach
here I have rewritten your code
<div class="order-summary">
<div class="order-col">
<div><strong>PRODUCT</strong></div>
<div><strong>TOTAL</strong></div>
</div>
#php $total = 0; $total_amount = 0; #endphp
<div class="order-products">
#if(session('cart'))
#foreach(session('cart') as $id => $details)
#php
$total += $details['price'] * $details['quantity'] ;
$total_amount += $details['price'] * $details['quantity'];
#endphp
<div class="order-col">
<div>
<h4 class="nomargin">{{$details['quantity'] }}x {{ $details['name'] }}</h4>
</div>
<div>KSh {{ $total }}</div>
</div>
#endforeach
#endif
</div>
<hr>
<div class="order-col">
<div>Shiping</div>
<div><strong>KSh 300</strong></div>
</div>
<hr>
<div class="order-col">
<div><strong>TOTAL</strong></div>
#php $total_amount += $total; #endphp
<div><strong class="order-total">KSh {{ $total_amount }} </strong></div>
</div>
</div>

Nested replies almost done, only need to arrange them in view

I'm currently doing a small forum in Laravel. This will include(ofcourse) commenting on posts. I also done replies on top of comments. I've done this by adding post_id, commenter_id and parent_id field in Comment model. And that's all alright.And i also done small margin that each reply have depending on their parent .What i have trouble with is displaying appropriate reply, for example: Comment1, then reply to comm.1, then another reply to that reply and so on, then another direct reply on Comment1, every subsequent reply to reply after second direct comment on Comment1 isn't grouped with other replies. How to achieve that?
Here is image of what i'm trying to achieve:
Here is Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Post;
use App\User;
class Comment extends Model
{
protected $fillable = [
'user_id',
'post_id',
'parent_id',
'body'
];
public function commentPost(){
return $this->belongsTo("App\Post","post_id");
}
public function commentAuthor(){
return $this->belongsTo("App\User","commenter_id");
}
public function replies() {
return $this->hasMany('App\Comment', 'parent_id');
}
}
Here is show view:
#extends("layouts.app")
#section("content")
<?php
/*Pregleda zasebno za title i description da li ima gresaka.
Ukoliko ih ima, dodeljume im klasu(crveni border).*/
$errBody = $errors->has('body') ? 'shake' : '';
?>
Go Back
<div style="float:right;">
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-right"></i>
</div>
<h1>{{$post->title}}</h1>
<div class="postContainer">
<img class="postCover" src="/storage/cover_images/{{$post->cover_image}}">
<div>
<!--Ovako prikazuje html kod.-->
<!--{{$post->body}}-->
{!!$post->body!!}
</div>
<small class="timestamp">Written on {{$post->created_at}}</small>
</div>
#if(!Auth::guest())
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<hr>
Edit
<form action="/posts/{{$post->id}}" method="post" class="float-right">
#csrf
{{method_field("DELETE")}}
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Are yoy sure you want to delete this post?</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
<button class="btn btn-outline-danger btn-sm float-right" data-toggle="modal" data-target="#myModal">Delete</button>
#endif
#endif
#auth
<hr>
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<form method="POST" action="/posts/{{$post->id}}/comments">
#csrf
<!-- https://laravel.com/docs/5.7/validation#available-validation-rules -->
<div class="form-group animated {{$errBody}}">
<textarea id="ckeditor" class="form-control" name="body" placeholder="Post body" required value=""></textarea>
</div>
<div>
<button type="submit" class="btn btn-outline-success btn-sm">Post comment</button>
</div>
</form>
#endif
<hr>
#endauth
<h6 style="border-bottom: 1px solid whitesmoke;">Comments <span class="badge" style="background-color: whitesmoke; border: 1px solid silver;vertical-align: top;">{{count($comments)}}</span></h6>
<div class="container commContainer">
<ul class="list-group" style="list-style-type:none">
#if(count($comments) > 0)
#foreach ($comments as $index => $comment)
<li>
#if($index>0)
<div class="horDiv"></div>
#endif
{{$comment->commentAuthor->name}} has said parent_id: {{$comment->parent_id}}
</li>
<li class="list-group-item py-2 commBody" style="margin-left: calc({{$comment->parent_id}}*10px) !important" parent_id="{{$comment->parent_id}}" id="{{$comment->id}}">My id: {{$comment->id}} {!!$comment->body!!}
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $comment->id }}')";>reply</span>
#include('inc.replyForm')
#endif
</li>
#endforeach
#endif
</ul>
</div>
#endsection
I'm just guessing, but can it be done by in view itself?I tried grouping and ordering before controller passes it to view, but nothing had desired effect. I appreciate every point in right direction.
Edit:
Here is store method in CommentsController.
public function store(Request $request, $id)
{
$this->validate($request, [
"body" => "required"
]);
$data = array(
"body" => $request->input("body"),
"post_id" => intval($id),
"commenter_id" => Auth::user()->id,
"imParent_id" => $request->input("comment_id")
);
//dd($data);
$comment = new Comment;
$comment->body = $data["body"];
$comment->post_id = $data["post_id"];
$comment->commenter_id = $data["commenter_id"];
$comment->parent_id = $data["imParent_id"];
$comment->save();
$post = Post::find($id);
$comments = $post->comments;
//return redirect("/posts/{{$id}}")->with("success", "Post Created")->with('comments', $comments);
//return view("posts.show")->with(compact('post', 'comments'));
//with(['replies' => function($comments){ $comments->orderBy('parent_id') } ])
return back()->with('comments', $comments);
}
Edit2:
And here is show method in PostController:
public function show($id)
{
$post = Post::find($id);
$comments = $post->comments;
$prev = $post->prev($post);
$next = $post->next($post);
return view("posts.show")->with(compact("post", "prev", "next", "comments"));
}
Edit3:
Here is rather flawed attempt(in show view):
#if(count($comments) > 0)
#for($i=0;$i<count($comments);$i++)
#if(!$comments[$i]->parent_id)
<li class="list-group-item py-2 commBody" parent_id="{{$comments[$i]->parent_id}}" id="{{$comments[$i]->id}}">
{!!$comments[$i]->body!!}
</li>
#for($k=0;$k<count($comments);$k++)
#if($comments[$i]->id==$comments[$k]->parent_id)
<?php array_push($myArray,$comments[$i]->id); ?>
<li class="list-group-item py-2 commBody" style="margin-left: calc({{$comments[$k]->parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
{!!$comments[$k]->body!!}
</li>
#endif
#endfor
{{"///////////////////////////////////////////////"}}
#endif
#if(array_search($comments[$i]->parent_id,$myArray)===false)
#for($k=0;$k<count($comments);$k++)
#if($comments[$i]->id==$comments[$k]->parent_id)
<li class="list-group-item py-2 commBody" style="margin-left: calc({{$comments[$k]->parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
{!!$comments[$k]->body!!}
</li>
#endif
#endfor
#endif
#endfor
#endif
And how it looks along with duplicates:
Edit4:
Followed Tim Lewis advice of separating comments(parentless) from replies(with parents), here's how to displayed them and sending additional parameter to reply form partial:
<ul class="list-group" style="list-style-type:none">
#if(count($comms) > 0)
#for($i=0;$i<count($comms);$i++)
<li class="list-group-item py-2 commBody" style="margin-left: calc({{"0"}}*10px) !important" parent_id="{{$comms[$i]->parent_id}}" id="{{$comms[$i]->id}}">
{{$comms[$i]->body}}
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $comms[$i]->id }}')";>reply</span>
#include('inc.replyForm', array('par' => $comms[$i]))
#endif
</li>
<li>#if($i>0) <div class="horDiv"></div> #endif </li>
#if(count($replies) > 0)
#for($j=0;$j<count($replies);$j++)
#if($comms[$i]->id==$replies[$j]->parent_id)
<li class="list-group-item py-2 commBody" style="margin-left: calc({{$comms[$i]->id}}*10px) !important" parent_id="{{$replies[$j]->parent_id}}" id="{{$replies[$j]->id}}">
{{$replies[$j]->body}}
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $replies[$j]->id }}')";>reply</span>
#include('inc.replyForm', array('par' => $replies[$j]))
#endif
</li>
<li>#if($j>0) <div class="horDiv"></div> #endif </li>
#endif
#for($k=$j;$k<count($replies);$k++)
#if($replies[$k]->parent_id==$replies[$j]->id)
<li class="list-group-item py-2 commBody" style="margin-left: calc({{$replies[$j]->id}}*10px) !important" parent_id="{{$replies[$k]->parent_id}}" id="{{$replies[$k]->id}}">
{{$replies[$k]->body}}
#if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
<br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $replies[$k]->id }}')";>reply</span>
#include('inc.replyForm', array('par' => $replies[$k]))
#endif
</li>
<li>#if($k>0) <div class="horDiv"></div> #endif </li>
#endif
#endfor
#endfor
#endif
#endfor
#endif
</ul>
I did it before for making categories. Here is a tip:
<select name="category_id" class="form-control chosen-select" required value="{{ old('category_id') }}">
#foreach(App\Category::where('parent_id',0)->get() as $c)
<option value="{{$c->id}}">*{{$c->name}}</option>
#foreach(App\Category::where('parent_id',$c->id)->get() as $d1)
<option value="{{$d1->id}}"> - {{$d1->name}}</option>
#endforeach
#endforeach
</select>

Resources