I am trying to generate slug in my URL instead of id. But I am getting this error message on my laravel window when I click on "Edit"----
"Attempt to read property "slug" on null"
in my web.php--
Route::get('/edit-client/{slug}', [App\Http\Controllers\backend\ClientController::class, 'EditClient'])->name('EditClient');
Route::post('/update-client/{slug}', [App\Http\Controllers\backend\ClientController::class, 'UpdateClient'])->name('UpdateClient');
in my model "OurClient.php" --
class OurClient extends Model{
use HasFactory;
protected $guarded = [];
public function getRouteKeyName()
{
return 'slug';
}
}
in my Controller --
public function editClient($slug)
{
$clients = OurClient::find($slug);
return view('backend.clients.edit',compact('clients'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function updateClient(Request $request, $slug)
{
OurClient::find($slug)->update([
'clientName' => $request->clientName,
'slug' => Str::slug($request->clientName),
'companyName' =>$request->companyName,
'description' => $request->description,
'designation' => $request->designation,
]);
return Redirect()->back();
}
in my index.blade.php--
Edit
in my edit.blade.php---
<form action="{{ route('UpdateClient',$clients->slug) }}" method="POST"
enctype="multipart/form-data">
#csrf
#method('patch')
<input type="hidden" name="old_image" value="{{ $clients->photo }}">
<div class="row">
...
</div>
<button type="submit">Update Client</button>
</form>
Instead of OurClient::find($slug) try using OurClient::where('slug',$slug)->first()
Related
blade.php file that shows all Posts from my database
Im trying to add a search bar that will filter all these posts to prioritise according to title but i cant seem to get it working at all
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12 pt-2">
<div class="row">
<div class="col-8">
#if (Auth::user() && Auth::user()->is_admin)
<h1 class="display-one">Bloggy</h1><h2>Admin</h2>
#endif
</div>
<!-- Check to see if the user is a guest, if they are the Add post button is hidden -->
#if(!Auth::guest())
<div class="col-4">
Add Post
</div>
#endif
</div>
#if (Auth::user() && Auth::user()->is_admin)
<div class="col-4">
Manage Users
</div>
#endif
<!-- HERE -->
<form>
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
#forelse($posts as $post)
<ul>
<li>{{ ucfirst($post->title) }}</li>
<li>{{ ucfirst($post->created_at) }}</li>
</ul>
<p>
{{ $post->user->name }}
</p>
<p>
{{ $post->tag->name }}
</p>
#empty
<p class="text-warning">No blog Posts available</p>
#endforelse
</div>
</div>
</div>
#endsection
Here is my posts controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')
->paginate(20);
return view('posts/index', [
'posts'=> $posts
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts/create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
// References
// Jefferey Way. laracasts. Laravel 8 from scratch. laracasts.com. https://laracasts.com/series/laravel-8-from-scratch
public function store(Request $request)
{
$request->validate([
'tag_id' => 'required',
'title'=> 'required',
'body'=> 'required',
]);
$post = new Post;
//dd(Auth::user());
$post->user()->associate(Auth::user());
$post->title = $request->title;
$post->body = $request->body;
$post->tag_id = $request->tag_id;
$post->save();
return redirect()->route('posts.index')
->with('success', 'Post created succesfully');
}
/**
* Display the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('posts.show', [
'post'=> $post,
]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.edit', [
'post' => $post
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required'
]);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated succesfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Deleted Succesfully');
}
public function showPostsByUser(User $user)
{
$posts = Post::where('user_id', $user->id)->get();
return view('posts.userposts', compact('posts', 'user'));
}
// Search function here
public function search()
{
// Check for search input
if (request('search')) {
$posts = Post::where('title', 'like', '%' . request('search') . '%')->get();
} else {
$posts = Post::all();
}
return view('posts.show')->with('posts', $posts);
}
}
Here is my routes file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\CommentController;
use App\Http\Controllers\RegisterController;
use App\Http\Controllers\AdminController;
use App\Models\Tag;
use App\Model\Post;
use App\Model\Users;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [WelcomeController::class, 'index']);
Route::resource('/posts', PostController::class);
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
Route::post('posts/{post}/comments', [CommentController::class, 'store']);
Route::get('/register', [RegisterController::class, 'create'])->name('register.create')->middleware('guest');
Route::post('/register', [RegisterController::class, 'store'])->name('register.store')->middleware('guest');
Route::get('/login', [LoginController::class, 'login'])->name('login');
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
Route::post('/login', [LoginController::class, 'authenticate'])->name('authenticate');
Route::resource('/admin', AdminController::class)->middleware('admin');
// Route::get('/tags/{tag}', function(Tag $tag) {
// return view('posts/index', [
// 'posts'=>$tag->posts
// ]);
// });
Route::get('/posts/user/{user}', [PostController::class, 'showPostsByUser'])->name('posts.showPostsByUser');
I cant seem to get anything working when i search in the bar on the main page my url changes to
http://localhost/posts?search=postname
And then nothing happens
Any help would be appreciated thanks, still trying to learn Laravel
EDIT:
It just seems to stay on the same page just the url changes
So you have a couple options here. You can define a separate route for /posts/search, or you can hook into the existing /posts (index) Route:
Define a GET Route for this new Search URL:
routes/web.php:
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
PostsController.php:
public function search(Request $request) {
$postsQuery = Post::latest(); // `latest()` is shorthand for `orderBy('created_at', 'DESC');`
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
Lastly, update the <form> element for this Search function:
<form action="{{ route('search') }}">
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
Now, when you navigate to http://localhost/posts/search, you'll get 20 Post records, ordered by created_at.
If you navigate to http://localhost/posts/search?search=example, you'll get up to 20 Post records, but only those that include example in their title.
You'll notice how similar that is to the index() method; so you can merge them to make your code a bit more "DRY" (Don't Repeat Yourself):
PostsController.php
public function index(Request $request) {
$postsQuery = Post::latest();
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
You don't need Route::get('/posts/search', ...); anymore. Instead, if you navigate to http://localhost/posts, you'll get the latest 20 Post records. If you navigate to http://localhost/posts?search=example, you'll get up to 20 Post records, ordered by created_at, but only those that include example in the title.
1)When I tried to use Model in update function of controller I get the error? What might be the reason for it.
I got error: Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically
2)Another problem is that my delete function doesn't delete the product. It redirects in another page. What might be the mistake in routes?
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products=product::all();
return view('products', ['products'=>$products]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('createProduct');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Product::create(request()->validate([
'title' => 'required',
'type' => 'required',
'firstname' => 'required',
'surname' => 'required',
'price' => 'required',
'papl' => 'required'
]));
return redirect('/products');
}
/**
* Display the specified resource.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $id)
{
return view('singleProduct', ['product'=>$id]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $id)
{
return view('editProduct', ['product'=>$id]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Product $id)
{
Product::update(request()->validate([
'title' => 'required',
'type' => 'required',
'firstname' => 'required',
'surname' => 'required',
'price' => 'required',
'papl' => 'required'
]));
return redirect('/products');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product=product::find($id)->delete();
return redirect('/products');
}
}
Model:Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//protected $guarded = [];
protected $fillable = ['title', 'type', 'firstname', 'surname', 'price', 'papl'];
//use HasFactory;
}
Route for delete:
Route::delete('/products/{id}',[ProductController::class, 'delete'])->name('deleteProduct');
deleteProduct.blade.php
#extends('layouts/masterlayout')
#section('title', 'All Products')
#section('mainbody')
<form method = "POST" action="../../products/{{$product->id}}">
#csrf
#method('DELETE')
<label>Product Name</label>
<input type = "text" name="title" value="{{$product->title}}">
<label>Product Type</label>
<input type = "text" name="type" value="{{$product->type}}">
<label>Price</label>
<input type ="number" name="price" value="{{$product->price}}">
<label>Firstname</label>
<input type ="text" name="firstname" value="{{$product->firstname}}">
<label>Surname</label>
<input type ="text" name="surname" value="{{$product->surname}}">
<label>Playlength/ PageNumber</label>
<input type ="number" name="papl" value="{{$product->papl}}">
</form>
#endsection
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::all();
return view('products', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('createProduct');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Product::create($request->validate([
'title' => 'required',
'type' => 'required',
'firstname' => 'required',
'surname' => 'required',
'price' => 'required',
'papl' => 'required'
]));
return redirect('/products');
}
/**
* Display the specified resource.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('singleProduct', compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('editProduct', compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Product $product, Request $request)
{
$product->update($request->validate([
'title' => 'required',
'type' => 'required',
'firstname' => 'required',
'surname' => 'required',
'price' => 'required',
'papl' => 'required'
]));
return redirect('/products');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect('/products');
}
}
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'title', 'type', 'firstname', 'surname', 'price', 'papl'
];
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
Route::resource('product', ProductController::class);
Blade File
#extends('layouts.masterlayout')
#section('title', 'All Products')
#section('mainbody')
<form method="POST" action="{{ route('product.destroy', $product->id) }}">
#csrf #method('delete')
<label>Product Name</label>
<input type="text" name="title" value="{{ $product->title }}">
<label>Product Type</label>
<input type="text" name="type" value="{{ $product->type }}">
<label>Price</label>
<input type="number" name="price" value="{{ $product->price }}">
<label>Firstname</label>
<input type="text" name="firstname" value="{{ $product->firstname }}">
<label>Surname</label>
<input type="text" name="surname" value="{{ $product->surname }}">
<label>Playlength/ PageNumber</label>
<input type="number" name="papl" value="{{ $product->papl }}">
</form>
#endsection
so here is my question, i have done everything and my senior request me to replace the parent_id now into description as the coder know what is the integer number represent but the users doesn't know. Here is the picture
My current view looks like !
As you can see inside the red column, there are two id :
1.( 999162, Testing3, Test3, 999161, active ) and
2.( 999163, testing4, test, 999162, active )
My desired output is the 1.( 999161 calls the 999161 description instead of id ).
Lets take 999163 as example : the desired output should be like 999163, testing4, test, test3, active.
I don't know how to call the description to replace the parent_id,can someone help ?
<div class="row">
<div class="col-md-12">
<br />
<h3 align="center">Category Data</h3>
<br />
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div align="right">
Add
<br />
<br />
</div>
<table class="table table-bordered table-striped">
<tr>
<th>Id</th>
<th>Code</th>
<th>Description</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
<th>Action</th>
</tr>
#foreach($category as $row)
<tr>
<td>{{$row['id']}}</td>
<td>{{$row['code']}}</td>
<td>{{$row['description']}}</td>
<td>{{$row['parent_id']}}</td>
<td>{{$row['status']}}</td>
<td>Edit</td>
<td>
<form method="post" class="delete_form" action="{{action('categoryController#destroy',$row['id'])}}">
{{ csrf_field() }}
{{ method_field('DELETE')}}
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
</div>
</div>
Here is my categoryController.php coding
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class categoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$category =Category::all()->toArray();
return view('category.index',compact('category'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all();
return view('category.create',compact('parents'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'code' => 'required',
'description' => 'required',
'parent_id' => 'required',
'status' => 'required',
]);
$category = new Category([
'id' => $request->get('id'),
'code' => $request->get('code'),
'description' => $request->get('description'),
'parent_id' => $request->get('parent_id'),
'status' => $request->get('status'),
]);
$category->save();
return redirect()->route('category.create')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$category = Category::find($id);
return view('category.edit', compact('category','id'));
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all();
return view('category.create',compact('parents'));
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all
return view('category.edit',compact('parents'));
}
public function subRequest()
{
return view('subRequest');
}
public function subRequestPost()
{
$input = request()->all();
return response()->json(['success'=>'Got Submit Request.']);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'code' =>'required',
'description' =>'required',
'parent_id'=>'required',
'status'=>'required'
]);
$category = Category::find($id);
$category->code =$request->get('code');
$category->description =$request->get('description');
$category->parent_id =$request->get('parent_id');
$category->status =$request->get('status');
$category->save();
return redirect()->route('category.index')->with('success','Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
return redirect()->route('category.index')->with('success','Data Deleted');
}
}
Category.php picture
Category.php picture
Suppose you have a Category model, add blew code to your Category model class.
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id', 'id');
}
Then, replace {{$row['parent_id']}} with {{$row->parent->description}} in your code.
This is the answer
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tmp =Category::all()->toArray();
$category = array();
foreach ($tmp as $key => $row) {
$policy = Category::find($row['parent_id']);
$tmpResult = new Category();
$tmpResult-> id =$row['id'];
$tmpResult-> code =$row['code'];
$tmpResult-> description =$row['description'];
$tmpResult-> parent_id =$policy['description'];
$tmpResult-> status =$row['status'];
array_push($category, $tmpResult);
}
return view('category.index',compact('category'));
}
I have a form payments with 4 fields -> date_paying, type_sitting, number_seance, fk_student.
In my form trainings I have 3 fields -> date_sitting, fk_payment, fk_student.
My problem is that when I want to add a recording, I retrieve 2 times the same value in my drop down list.
I really want to keep only an item
In my create.blade(trainings) I have this:
<div class="form-group {{ $errors->has('fk_payment') ? 'has-error' : '' }}">
<label for="company-content">Payment </label>
<select name="fk_payment" id="fk_payment" class="form-control" required="required" value="{{ old('fk_payment')}}"/>
<option value="">Choice Payment</option>
#foreach($payments as $payment)
<option value="{{$payment->id}}" {{ old('fk_payment') == $payment->id ? 'selected' : '' }} >
{{$payment->type_sitting}}
</option>
#endforeach
{!! $errors->first('fk_payment', '<span class="help-block">:message</span>') !!}
</select>
Here is my Controller Training
class TrainingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$trainings = Training::oldest()->paginate(5);
return view('admin.trainings.index', compact('trainings'));
with('i', (request()->input('page', 1) -1) *5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$payments = Payment::all();
$students = Student::all();
return view('admin.trainings.create', compact('payments', 'students','trainings'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'date_sitting' => 'required',
'fk_payment' => 'required',
'fk_student' => 'required'
]);
$exists = Training::where('date_sitting', $request->get('date_sitting'))->where('fk_payment', $request->get('fk_payment'))->where('fk_student', $request->get('fk_student'))->count();
if (!$exists){
//$payment = Payment::where('fk_student', $request->get('fk_student'))->first();
$payment = Payment::where('fk_student', $request->get('fk_student'))
->take(1)
->get();
if(!isset($payment)){
return redirect()->route('trainings.index')
->with('error', 'No Payment, no training for you!');
}
else{
Training::create($request->all());
return redirect()->route('trainings.index')
->with('success', 'new data created successfully');
}
}
}
Controller Payment
class PaymentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$payments = Payment::oldest()->paginate(5);
return view('admin.payments.index', compact('payments'));
with('i', (request()->input('page', 1) -1) *5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$students = Student::all();
return view('admin.payments.create', compact('students', 'payments'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'date_payment' => 'required',
'type_sitting' => 'required',
'number_seance' => 'required',
'fk_student' => 'required'
]);
$exists = Payment::where('date_payment', $request->get('date_payment'))->where('type_sitting', $request->get('type_sitting'))->where('number_seance', $request->get('number_seance'))->where('fk_student', $request->get('fk_student'))->count();
if (!$exists){
Payment::create($request->all());
return redirect()->route('payments.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('payments.index')
->with('error', 'doublon');
}
}
Model - Payment
class Payment extends Model
{
//
protected $fillable = ['date_payment', 'type_sitting', 'number_seance', 'fk_student'];
protected $dates = ['date_payment'];
public function students(){
return $this->belongsTo('App\Student', 'fk_student');
}
public function trainings(){
return $this->hasMany('App\Training', 'fk_payment');
}
}
Model - Training
class Training extends Model
{
//
protected $fillable = ['date_sitting', 'fk_payment', 'fk_student',];
protected $dates = ['date_sitting'];
public function students(){
return $this->belongsTo('App\Student', 'fk_student');
}
public function payments(){
return $this->belongsTo('App\Payment', 'fk_payment');
}
}
Change your this specific blade:
<div class="form-group {{ $errors->has('fk_payment') ? 'has-error' : '' }}">
<label for="company-content">Payment </label>
<select name="fk_payment" id="fk_payment" class="form-control" required="required" value="{{ old('fk_payment')}}"/>
<option value="">Choice Payment</option>
#foreach($payments as $payment)
#php
$training = App\Training::where('fk_payment', $payment->fk_payment)->first();
#endphp
<option value="{{$payment->id}}" {{ old('fk_payment') == $payment->id ? 'selected' : '' }} >
{{ $training->type_sitting )}}
</option>
#endforeach
{!! $errors->first('fk_payment', '<span class="help-block">:message</span>') !!}
</select>
See more
Hello dear i have an problem when user need too delete or edit post , laravel show error " you can't edit post ... " i use a model and controller in laravel and user "auth" system id for access post for delete or edit now see my work :
Index View
#extends('layouts.app')
#section('content')
#auth
<h6 class="alert alert-dark">Dear Guest {{ Auth::user()->name }} for send a post <a class="btn btn-success" href="{{ route('ads.create') }}">Click</a> Here</h6>
#endauth
#guest
<div class="alert alert-primary">for send a post you can <a class="btn btn-success" href="{{ route('register') }}">Register</a></div>
#endguest
#if(count($adses) > 0)
<div class="row">
#foreach($adses as $ads)
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="card mb-4">
<img class="card-img-top img-fluid" src="/storage/cover_images/{{$ads->cover_image}}" alt="Card image cap">
<div class="card-body">
<h6 class="card-title">{{ $ads->title }}</h6>
#if(!Auth::guest())
#if(Auth::user()->id == $ads->user_id)
<div class="row">
{!!Form::open(['action' => ['AdsController#destroy', $ads->id], 'method' => 'POST',]) !!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close() !!}
Edit
</div>
#endif
#endif
</div>
</div>
</div>
#endforeach
{{ $adses->links() }}
#else
<p class="alert alert-warning" role="alert">any post !</p>
</div>
#endif
#endsection
Ads Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ads extends Model
{
protected $table = 'ads';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function adses(){
return $this->hasMany('App\Ads');
}
}
Ads Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Ads;
class AdsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$adses = Ads::orderBy('created_at', 'desc')->paginate(16);
return view('ads.index')->with('adses', $adses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('ads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'image|nullable|max:1999',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$ads = new Ads();
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
$ads->user_id = auth()->user()->id;
$ads->cover_image = $fileNameToStore;
$ads->save();
return redirect('/home')->with('success', 'آگهی شما با موفقیت درج شد .');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$ads = Ads::find($id);
return view('ads.show')->with('ads', $ads);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant edit other user's post');
}
return view('ads.edit')->with('ads', $ads);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'required',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$ads = Ads::find($id);
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
if($request->hasFile('cover_image')){
$ads->cover_image = $fileNameToStore;}
$ads->save();
return redirect('/')->with('success', 'your post is update');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant delete other user's post');
}
if($ads->cover_image != 'noimage.jpg'){
// Delete Image
Storage::delete('public/cover_images/'.$ads->cover_image);
}
$ads->delete();
return redirect('/')->with('success', 'Post Removed');
}
}
Routs
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('/', 'AdsController');
Route::resource('ads', 'AdsController');
now , after send a post and login in system user cant delete or edit her post .
Thank you
auth()->user()->id !== $ads->user_id .
Уou have this line. And if user not login when he creating post, you are will be have user_id == null. Check in DB than user_id?
I solved my problem
if(auth()->user()->id !== $ads->user_id)
Since you're using !==, make sure your user_id is integer