how to create SELECT * FROM `TABLE` WHERE user_id = id; in Laravel 8 - laravel

I want to create a page that can show data where user_id = user_id logged in
here is my controller that select all data from table, i want to filter it with corresponding logged in user id
public function staffHome()
{
$posts = Post::latest()->paginate(5);
return view('staffHome', compact('posts'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
and here is my view
#foreach ($posts as $post)
<tr>
<td class="text-center">{{ ++$i }}</td>
<td>{{ $post->title }}</td>
<td class="text-center">
<form action="{{ route('posts.destroy',$post->id) }}" method="POST">
<a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">Show</a>
<a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">Delete</button>
</form>
</td>
</tr>
#endforeach
thanks in advance

your code should be like this
public function staffHome()
{
$posts = Post::where('user_id', Auth::id())->latest()->paginate(5);
return view('staffHome', compact('posts'))->with('i', (request()->input('page', 1) - 1) * 5);
}

You can do it like this
$posts = Post::where('user_id', Auth::id())->latest()->paginate(5);
Where Auth::id() is currently logged in user's id.
Or with relation
Auth::user()->posts()->->latest()->paginate(5);

$posts = Post::where('user_id', $user_id)->latest()->paginate(5);
Please see: https://laravel.com/docs/8.x/collections#method-where

Related

Display data using pivot table

I have 2 tables which users and groups and I also has created a pivot table for them.
What I want to display is list of the group that user have not joined yet.
my controller
public function redirectFunct()
{
$user = User::find(Auth::user()->id);
$groups=Group::all();
$exists = DB::table('group_user')
->whereuser_id(Auth::user()->id)
->count() > 0;
return view('member.dashboard',['user'=>$user,'groups'=>$groups,'exists'=>$exists]);
}
blade file
#foreach($groups as $groups)
#if($!exists)
<tbody>
<tr>
<td>{{$groups->id}}</td>
<td>{{$groups->groupName}}</td>
<td>{{$groups->groupDesc}}</td>
<td><button type="button" class="btn btn-primary .btn-{color}">Details</button></td>
<td><a href="{{url('/join',$groups->id)}}"><button type="button" class="btn btn-secondary .btn-{color}">Join</button></td>
</tr>
</tbody>
#endif
#endforeach
I do not sure how to check if the data is exist or not in the pivot table. Please help me.
you could try this in your $exist I'm not sure what ->count() > 0; is use for
$exists = DB::table('Group')
->where('userID', Auth::user()->id)
->get();
If you want to display only the group that the user doesn't exist in group you could try this
<tbody>
#foreach($groups as $group)
#if('your group parent id' != 'your user id that related to the group')
<td>{{$group->id}}</td>
<td>{{$group->groupName}}</td>
<td>{{$group->groupDesc}}</td>
<td><button type="button" class="btn btn-primary .btn-{color}">Details</button></td>
<td><a href="{{url('/join',$groups->id)}}"><button type="button" class="btn btn-secondary .btn-{color}">Join</button></td>
#endif
#endforeach
</tbody>
this is the screenshot of that page
The pivot table

Invalid argument supplied for foreach() (View: xxx\resources\views\admin\info-admin.blade.php) http://127.0.0.1:8000/tambah-info

Invalid argument supplied foreach()when try to add data
here's the form for submitting the data
info-admin.blade.php
<tbody class="text-center align-middle">
#foreach ( $info as $infos )
<tr>
<th scope="row" class="align-middle">{{ $loop->iteration }}</th>
<td class="align-middle">{{ $infos->judul }}</td>
<td class="align-middle">{{ $infos->konten }}</td>
<td class="align-middle">{{ $infos->image }}</td>
<td class="align-middle">{{ $infos->created_at }}</td>
<td class="align-middle">{{ $infos->Updated_at }}</td>
<td class="align-middle form">
<button type="submit" class="btn btn-info mb-3">Edit</button>
<form method="POST" action="{{ route('infos.destroy', [$infos->id]) }}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger">Hapus</button>
</form>
</td>
</tr>
#endforeach
</tbody>
Store logic
InfosController
public function store(Request $request)
{
$info = new Info();
$info->judul = $request->input('judul');
$info->konten = $request->input('konten');
$info->image = $request->input('image');
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('upload/info_penting' , $filename);
$info->image = $filename;
} else{
return $request;
$info->image = '';
}
$info->save();
return view('admin.info-admin')->with('info','$info');
}
my routes, in case if you want to see it
web.php
route::post('/tambah-info','InfosController#store')->middleware('auth','admin');
EDITED
undefined variable when trying to update
the controller for the logic for updating the data
InfosController
public function update(Request $request, Info $info)
{
//
Info::where('id', $info->id)
->update([
'judul' => $request->judul,
'konten' => $request->konten,
'image' => $request->image,
]);
return redirect('/info-admin')->with('success', 'Berhasil Diedit');
}
here's the form for for the updating the data
edit-info.blade.php
<form action="{{ route('infos.update', [$info->id]) }}" method="patch" enctype="multipart/form-data>
#csrf
<input type="hidden" name="_method" value="PATCH">
<div class="mb-3">
<label for="judul">Judul</label>
<input type="string" class="form-control" value="{{$info->judul}}" id="judul" name="judul" required>
<div class="invalid-feedback">
Kolom Wajib Diisi
</div>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Konten</label>
<textarea class="form-control" value="{{$info->konten}} id="exampleFormControlTextarea1" rows="3" name="konten" required></textarea>
<div class="invalid-feedback">
Kolom Wajib Diisi
</div>
</div>
<input class="mb-3" type="file"value="{{$info->image}} name="image">
<button type="submit" class="btn btn-success btn-lg btn-block mt-auto">Kirim</button>
</form>
</div>
After saving your post, you should redirect to another route, probably the route for displaying all the posts
return redirect()->route('info-admin');
You should have another controller method for displaying all your data, you will have something similar to this
public function index()
{
$infos = Info::all();
return view('admin.info-admin', ['infos' => $infos]);
}
Then for sending a collection to the view. You should use your foreach this way and not the other way
#foreach($infos as $info)
// your code here
#endforeach
UPDATES
Your admin view should be like this
<tbody class="text-center align-middle">
#foreach ( $infos as $info )
<tr>
<th scope="row" class="align-middle">{{ $loop->iteration }}</th>
<td class="align-middle">{{ $info->judul }}</td>
<td class="align-middle">{{ $info->konten }}</td>
<td class="align-middle">{{ $info->image }}</td>
<td class="align-middle">{{ $info->created_at }}</td>
<td class="align-middle">{{ $info->updated_at }}</td>
<td class="align-middle form">
<button type="button" class="btn btn-info mb-3">Edit</button>
<form method="POST" action="{{ route('infos.destroy', $info->id) }}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger">Hapus</button>
</form>
</td>
</tr>
#endforeach
</tbody>
Add data
define two routes, one route to access the form and another route to store form data
Route::get('/add-info', 'InfosController#create)->name('infos.add');
Route::post('/store-info', 'InfosController#store)->name('infos.store');
Access your add form as
<button type="button" class="btn btn-Success mb-3">Add</button>
Your create method
public function create()
{
return view('infos.add');
}
Your store method
public function store(Request $request)
{
$info = new Info();
$info->judul = $request->input('judul');
$info->konten = $request->input('konten');
$info->image = $request->input('image');
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('upload/info_penting' , $filename);
$info->image = $filename;
} else{
return $request;
$info->image = '';
}
$info->save();
return redirect()->route('admin.info-admin');
Edit data
define two routes, one route to access the form and another route to update form data
Route::get('/edit-info/{infos}/edit', 'InfosController#edit')->name('infos.edit');
Route::post('/update-info/{infos}/update', 'InfosController#update)->name('infos.update');
Access your edit form as
<button type="button" class="btn btn-Success mb-3">Edit</button>
Your edit method
public function edit($id)
{
$info = Info::findOrFail($id)
return view('infos.edit', ['infos' => $info]);
}
Your update method
public function update(Request $request, $id)
{
Info::where('id', $id)
->update([
'judul' => $request->judul,
'konten' => $request->konten,
'image' => $request->image,
]);
return redirect()->route('admin.info-admin')->with('success', 'Berhasil Diedit');
}
Add form action
<form action="{{ route('infos.store') }}" method="POST" enctype="multipart/form-data">
Edit form action
<form action="{{ route('infos.update', ['infos' => $info->id]) }}" method="POST" enctype="multipart/form-data">

product is not deleting from cart

hi m trying to delete product from cart but its not deleting , any suggestion to fix it,when i click on submit button then it says 404|not found
controller:
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->delProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
model
public function deleteProduct($product)
{
if ($this->contents) {
if (array_key_exists($product->product_slug, $this->contents)) {
$delProduct = $this->contents[$product->slug];
$this->totalQty -= $delProduct['qty'];
$this->totalPrice -= $delProduct['price'];
array_forget($this->contents, $product->slug);
}
}
}
blade file
#foreach($contents as $slug => $cartItem)
<form action="{{ route('deleteCartProduct', $product) }}" method="POST">
#csrf
<tr class="table-row">
<td class="column-1">
<div class="cart-img-product b-rad-4 o-f-hidden">
<img src="{{ URL::to('/') }}/images/backend_images/product_images/{{ $cartItem['product']->product_image }}" alt="IMG-PRODUCT">
</div>
</td>
<td class="column-2">{{ $cartItem['product']->product_name }}</td>
<td class="column-3">${{ $cartItem['product']->product_price }}</td>
<td class="column-4">
<div class="flex-w bo5 of-hidden w-size17">
<button class="btn-num-product-down color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-minus" aria-hidden="true"></i>
</button>
<input class="size8 m-text18 t-center num-product" type="number" name="num-product1" value="{{ $cartItem['qty'] }}">
<button class="btn-num-product-up color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</td>
<td class="column-5">${{ $cartItem['price'] }}</td>
<td class="column-5">
<input type="submit" class="btn btn-danger value="Remove Product">
</td>
</tr>
</form>
#endforeach
route:
Route::get('/cart/delete-product/{id}','ProductController#deleteCartProduct')->name('deleteCartProduct');
Your route should be Route::delete instead of Route::get and then in the form add this as well:
#method('delete')
I saw your error on the button:
<input type="submit" class="btn btn-danger value="Remove Product">
Change it with this:
<input type="submit" class="btn btn-danger" value="Remove Product">
Missing quote..
EDIT
Your route should be this:
Route::delete('/cart/delete-product/{id}','Admin\ProductController#deleteCartProduct')->name('deleteCartProduct');
You need to change the code in a controller as below.
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->deleteProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
You defined it as method="POST" in blade. and "get" in route. So you need to change verb to Route::post

#method('DELETE') and version 5.4.13

In my form index.blade, I see that my method delete() has a problem to display???
In my index.blade I have this:
#foreach($students as $student)
<tr>
<td> {{$student->name}}</td>
<td> {{$student->firstname}}</td>
<td>
<form method="POST" action="{{ route('students.destroy', $student) }} ">
<a class="btn btn-sm btn-warning" href="{{route('students.edit',$student->id)}}">Editer</a>
{{csrf_field()}}
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Effacer</button>
</form>
</td>
</tr>
#endforeach
In my Controller I have this:
public function destroy($id)
{
$students = Student::find($id);
$students->delete();
return redirect()->route('students.index')
->with('success', 'Effacé !');
}
For information, I have the version '5.4.13'.
Thank you
In laravel 5.4 you need to use
{{ method_field('delete') }}
From 5.6 #method('delete') is introduced.

Laravel 5. Error: my model with trashed and one relation.

Problem exists because transhed added, conflicted with tablerelation.
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function category() {
return $this->hasOne('App\Models\Category', 'id', 'category_id');
}
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Category;
use App\Models\Post;
use Session;
use Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = new Post();
// $allPosts = $posts::onlyTrashed()->get();
// $allPosts = $posts::withTrashed()->get();
$allPosts = $posts::all();
$postDeleted = $posts::onlyTrashed()->count();
return view('admin.post.index', ['posts' => $allPosts, 'postDeleted' => $postDeleted]);
}
...
View:
#foreach ($posts as $post)
<tr class="table-pages-list-item">
<td><input type="checkbox"></td>
<td>{{ $post->h1 }}</td>
<td>{{ $post->url }}</td>
<td>{{ $post->category->h1 }}</td>
<td>
#if ($post->published)
<span class="label label-success">Да</span>
#else
<span class="label label-danger">Нет</span>
#endif
</td>
<td>{{$post->updated_at}}</td>
<td>
<a href="#"type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="left" title="Редактировать">
<i class="fa fa-edit"></i>
</a>
<a href="#" target="_blank" type="button" class="btn btn-success" data-toggle="tooltip" data-placement="top" title="Просмотреть">
<i class="fa fa-external-link"></i>
</a>
<form action="{{ action('PostController#destroy', ['id' => $post->id]) }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn btn-danger" data-toggle="tooltip" data-placement="right" title="В корзину">
<i class="fa fa-trash-o"></i>
</button>
</form>
</td>
</tr>
#endforeach
Error here <td>{{ $post->category->h1 }}</td>
Trying to get property of non-object (View: C:\OpenServer\domains\laravel\resources\views\admin\post\index.blade.php)
because you are naming your foreign key as category_id like the convention,i think you should define eloquent relationship like this
public function category() {
return $this->hasOne('App\Models\Category');
}
you should see hasOne method on Model.php file how to define one to one relationship.
Please check what fields your category table has!
Does it contains 'h1' field, you are accessing 'h1' key, but may be its not there at table

Resources