Laravel- arranging records in ascending and descending order - php

I have a create method in my controller
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main]);
}
This is my photos.blade file
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form><form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value= " Descending" class="settings-photos-header2 text-center"/>
</form>
<h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
#foreach ($image_array as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</form>
</div>
#endforeach
Question- How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through any other means?

There are many ways you can achieve the sorting issue but as you have setup your page let me tell you the way you can sort records. Create another action which point to your settings.photos route
public function settings_photos($property_id) {
$form = Input::get('submit');
$orderBy = $form == "Ascending" ? "asc" : "desc";
# Fetch Images in of Specific Property
$list_of_images = Image::where('property_id', $property_id)
# Order by Asc/Desc
->sortBy('id', $orderBy)->get();
return view('settings.photos', ['image_array' => $list_of_images]); }
Now add Image->id to pass in your controller action by form
https://stackoverflow.com/questions/50432659/laravel-arranging-records-in-ascending-and-descending-order#
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="image_id" value="{{$id}}" />
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form>
<form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="image_id" value="{{$id}}" />
<input type="submit" value="Descending" class="settings-photos-header2 text-center"/>
</form>
Now make some changes to your previous Controller code
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main, 'id' => $id]);
}
As I told you there are various way to sort records even by Ajax but I suggest you using your code example. I also did not optimize the code.
Let me know if you have any question.
Thanks

Related

how making many submit button in one page laravel 8

I have several buttons to insert data into the database, but only one command works, while the others don't work, what should I do, I will give an example of the data I created
this is my controller :
public function store(Request $request)
{
//
$days = $request->hari;
$hours = $request->jam;
$minutes = $request->menit;
$model = new Q_Topic_User;
$model->status = $request->status;
$model->topic_id = $request->topic_id;
$model->timer = Carbon::now()->addDays($days)->addHours($hours)->addMinute($minutes);
$topik = $request->topic_id;
$model->user_create = auth()->id();
// dd($request->all());
$model->save();
return redirect('qanswers/'. $topik);
}
public function storeAns(Request $request)
{
$modellama = Q_Answer::where('user_create', '=', $request->kode_user)
->Where('topic_id', '=', $request->topic_id)
->Where('question_id', '=', $request->question_id);
$a = $request->user_answer;
$b = $request->answer;
if ($a === $b){
$nilai = "1";
}
else{
$nilai = "0";
}
if ($modellama >= "1"){
$modellama->delete();
}
// dd($request->all());
$model = new Q_Answer;
$model->topic_id = $request->topic_id;
$model->question_id = $request->question_id;
$model->user_answer = $request->user_answer;
$model->answer = $request->answer;
$model->hasil = $nilai;
$model->user_create = auth()->id();
$topik = $request->topic_id;
$model->save();
return redirect('qanswers/'. $topik);
}
public function storeTot(Request $request)
{
$tot_nilai = Q_Answer::select(DB::raw("CAST(SUM(hasil) as int) as tot_nilai"))
->Where('topic_id', '=', $request->topic_idi)
->Where('user_create', '=', auth()->id())
->pluck('tot_nilai');
// dd($tot_nilai);
$tot_soal = Q_Question::select(DB::raw("CAST(COUNT(topic_id) as int) as tot_soal"))
->Where('topic_id', '=', $request->topic_idi)
->pluck('tot_soal');
dd($request->all());
$model = new Q_Answer_Tot;
$model->topic_id = $request->topic_idi;
$model->totalsoal = $tot_soal;
$model->totalnilai = $tot_nilai;
$model->user_create = auth()->id();
// dd($request->all());
$model->save();
$topik = $request->topic_id;
return redirect('qanswers/'. $topik);
}
blade :
<form method="POST" action="{{ url('qanswers') }}"
enctype="multipart/form-data">
#csrf
#foreach ($datas as $d_value)
<button type="submit" class="btn btn-sm bg-success">Kirim data</button>
#endforeach
</form>
<form method="POST" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
<form method="POST" action="{{ url('qanswers.storeTot') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $t_value)
<button type="submit" class="btn btn-sm bg-success">Kirim Pilihan Peserta</button>
#endforeach
</form>
my web.php :
Route::resource('/qanswers', Q_AnswersController::class);
Route::post('/storeAns',[Q_AnswersController::class, 'storeAns'])->name('storeAns');
Route::post('/storeTot',[Q_AnswersController::class, 'storeTot'])->name('storeTot');
i can save data in store but i can save data using storeAns and storeTot. I dont find error in laravel log but i can see my data using dd($request->all()); can u help me?
Its good practice to give each form an unique id. With multiple forms and buttons, I would specify the form for the button. And you need to use value to figure out which button was pressed, especially when you are going to the same url in more than one form.
<form method="POST" id="answers" action="{{ url('qanswers') }}"
enctype="multipart/form-data">
#csrf
#foreach ($datas as $d_value)
<button type="submit" class="btn btn-sm bg-success" value="form1">Kirim data</button>
#endforeach
</form>
<form method="POST" id="storeans1" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success" value="form2">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
<form method="POST" id="storeans2" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success" value="form3">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
I have shown the value with formx. SInce you are creating many buttons for each form, each should have an unique value such as
form1btn1
form1btn2
form1btn3

Trying to get property 'deskripsi' of non-object (View:

#extends('layouts.admin')
#section('content')
#foreach($galerys as $data)
<form method="post" enctype="multipart/form-data" action="{{url('/ubahGaleryPost')}}">
{{ csrf_field() }}
<h4>Ubah Gambar</h4>
<input name="id" id="id" type="hidden" value="{{$data->id}}" >
<h5>Gambar</h5>
<input name="gambar" id="gambar" type="file">
<h5>Deskripsi</h5>
<input name="deskripsi" id="deskripsi" class="form-control" type="text" value="{{$data->deskripsi}}">
<button type="submit" class="btn btn-primary">Ubah</button>
</form>
#endforeach
#endsection
controller
public function ubahGalery($id){
$data = Galery::findOrFail($id);
return view('admin.updategalery',['galerys'=>$data]);
}
public function ubahGaleryPost(Request $request){
$data = Galery::where('id',$request->id)->first();
if (empty($request->file('gambar'))){
$data->gambar = $data->gambar;
}
else{
unlink('img/galery/'.$data->gambar);
$file = $request->file('gambar');
$ext = $file->getClientOriginalExtension();
$newName = rand(100000,1001238912).".".$ext;
$file->move('img/galery',$newName);
$data->gambar= $newName;
}
$data->deskripsi = $request->deskripsi;
$data->update();
return redirect('/galeryAdmin');
}
$data = Galery::findOrFail($id); this will return Galery object instead of a Collection of Galery (except if $id is an array).
So in your HTML you don't need a foreach and instead could just do $data->id, $data->deskripsi etc.
You don't need to loop on galerys as you are fetching only one result so you don't need to loop on your result so instead of that just fetch data directly.
Like this,
$galerys->deskripsi
Hope this helps:)

Pass id from controller index to store - Laravel

This is my route :
Route::post('/store', 'EditlinkController#store');
My controller
public function index()
{
$id = $_GET['id'];
$links = DB::table('slugs')->where('slugs.id',$id)
->join('links','links.sid','=','slugs.id')
->get();
return view('editlink', ['links' => $links]);
}
public function store(Request $request, $id)
{
$url = $request->input('url');
$data =new link;
$sid = $id;
$data->sid = $sid;
$data ->url = $url;
$data ->save();
return redirect('/links');
}
And my view:
<form role="form" method='POST' action="{{url('store')}}">
<div class="entry input-group col-xs-3">
<input class="form-control" name="url" type='url' placeholder="https://..." size="100"/>
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-primary" type="button">
<span class="material-icons md-12">add</span>
</button>
{{ csrf_field() }}
</div>
</form>
So basically here I want to call $id from index to store. I also have tried
Route::post('/store/{id}', 'EditlinkController#store');
But still doesn't work. Thank you.
Your route, /store/{id}, requires you to have a route parameter. Make sure you have an $id available to you before you generate your url for your form.
An example of what your open form tag should look like with the $id included:
<form role="form" method='POST' action="{{url('store', $id)}}">
I'm assuming the view editlink is where the markup for the form resides. If so, then you can simply pass the value of the id to your view from your controller:
return view('editlink', ['links' => $links, 'id' => $id]);

How to make a working search form PHP/HTML?

So basically I'm doing a project for college and the only thing missing from my project is a working search form, but i don't know how to do it. All of my products are created and seeded into the database.
My routes:
Route::get('/', [
'uses' => 'ProductsController#getIndex',
'as'=> 'product.index'
] //tenho de meter um . porque nao é uma diretoria global, index ta dentro
duma pasta shop
);
my table:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string("imagePath");
$table->string("title");
$table->text("description");
$table->integer("price");
});
my form structure:
<form action="" method="post" class="navbar-form navbar-left " role = "search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
my products controller:
public function getIndex(){
$products = Products::all();
return view('shop.index', ['products' => $products]);
}
I've seen a lot of tutorials on how to do one but i cant seem to make it filter the ones i have, for example, if i have 3 boots and 5 shoes on the shop, if i write "boot" on the search, i want only for the 3 boots to appear
your HTML would be
<form action="{{ route('product.search') }}" method="post" class="navbar-form navbar-left " role = "search">
#csrf
<div class="form-group">
<input type="text" class="form-control" name="search" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
in your searchProduct function
for like query where it can search in title and if keyword present it will return all product who has same title you are searching for
public function searchProducts(Request $request){
$products = Product::where('title', 'like', '%'.$request->search.'%')->get();
return view('shop.index', ['products' => $products]);
}
for exact same title result
public function searchProducts(Request $request){
$products = Product::where('title',$request->search)->get();
return view('shop.index', ['products' => $products]);
}
there are a LOT of different ways to approach something like a search ... ranging from simple to very complex but a basic method would to search your title and description fields for a keyword like "boot".
You'll want to add a couple of things ...
First, add a new route to handle the search request:
Route::post('/results', [
'uses' => 'ProductsController#searchProducts',
'as'=>'product.search'
]);
Next, add a name to your html input, such as 'keyword' along with the blade shortcut for the CSRF token field:
<form action="/results" method="post" class="navbar-form navbar-left " role = "search">
#csrf
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="keyword">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
Then add a function to your controller to handle the query:
public function searchProducts(Request $request){
$results = Product::where('title', 'like', '%'.$request->search.'%')
->orWhere('description', 'like', '%'.$request->search.'%')
->orderBy('title', 'desc')
->get();
return view('search_results', ['results'=>$results, 'keyword'=>$request->keyword]);
}
Finally, create a new file named search_results.blade.php and place it in your views directory. This will be used to display the search results to the user.
<h2>Search Results for {{$keyword}}</h4>
<table>
<thead>
<tr>
<th>Product</th>
<th>Description</th>
<th>Price</td>
</tr>
</thead>
<tbody>
#forelse($results as $result)
<tr>
<td>{{$result->title}}</td>
<td>{{$result->description}}</td>
<td>{{$result->price}}</td>
</tr>
#empty
<tr>
<td colspan="3">
No Products Found
</td>
</tr>
#endforelse
</tbody>
</table>
With this foundation, you could really go wild and add filtering options, sorting, ranking and more. Hope that helps get you going!
you can do this
html
<form action="/search" method='post' class="navbar-form navbar-left " role = "search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
PHP
public function search(Request $request)
{
$products = Product::where('title', 'LIKE', '%'.request->search.'%')->get();
return view('search', ['products' => $products]);
}
Only change wich view you want return and create too in to a routes/web.php.

Laravel - Arranging images in ascending and descending order with links

I have a create method in my controller
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main]);
}
This is my blade view
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form><form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value= " Descending" class="settings-photos-header2 text-center"/>
</form>
<h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
#foreach ($image_array as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</form>
</div>
#endforeach
Question-
How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through <a href> links?
First, foreach overrides $id in each iteration, so finally value of $id is $property_id value of last item from $image array.
You need to define relations.
In PropertyUser class add:
public function images() {
return $this->belongsTo(Image::class, 'property_id');
}
Then, in your create method in controller:
public function create(Request $request) {
// use direction query parameter to define asc or desc sorting
$order_direction = $request->query('direction');
$property_user = PropertyUser::where('user_id', '=', Auth::user()->id)
->with(['images' => function($query) use ($order_direction) {
$query->orderBy('id', $order_direction)
})->get();
// here you can access an array with associated images:
$images = $property_user->images;
return view('settings.photos', ['image_array' => $images]);
}
Your link to sorted images should like: Sort asc

Categories