Limit to only one value in my drop-down list - laravel

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

Related

laravel slug not working-Attempt to read property "slug" on null

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()

Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically and delete function not working

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

How to call out the "description" to replace the "parent_id" in laravel?

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'));
}

How to update the value of selected dropdown using Laravel?

I want to update selected drop down value and save that into database
in this code i cant update my drop down list value from database
my controller code
public function edit($product_id)
{
$all_categories = DB::table('tbl_category')->get();
$all_manufactures = DB::table('tbl_manufacture')->get();
$product = DB::table('tbl_product')
->where('product_id',$product_id)
->get()->first();
return View('admin.edit-product')->with([
'product'=>$product,
'all_categories'=>$all_categories,
'all_manufactures'=>$all_manufactures,
]);
}
my view code
<select id="brand_name" name="brand_name" data-rel="chosen">
#foreach($all_manufactures as $manufacture)
#if($manufacture->manufacture_status)
<option value="{{$manufacture->manufacture_id}}"> {{$manufacture->manufacture_name}}</option>
#endif
#endforeach
</select>
The edit method displays a form for editing.
/**
* Show the form for editing the specified resource.
*
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function edit(User $user)
{
$roles = Role::all();
return view('admin.users.form', [
'roles' => $roles,
'user' => $user
]);
}
You need update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::find($id);
$user->update($request->all());
$role = Role::findOrFail($request->roles);
$user->syncRoles([$role->id]);
return redirect()->route('users.index');
}
View
<form action="{{route('users.update', $user->id)}}" method="post">
#csrf
#method('PUT')
<select class="custom-select" name="roles">
#if ($roles)
#foreach($roles as $role)
<option {{ ((old('roles') == $role->id) or (isset($user) and $user->roles->pluck('id')->contains($role->id)) ) ? 'selected' : null }} value="{{$role->id}}">{{$role->display_name}}</option>
#endforeach
#endif
</select>
</form>

Cant't edit or delete post in laravel project

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

Resources