Obka
256
9
Laravel

Can't edit or delete post in laravel project

Posted 1 year ago by Obka

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"><a href="/ads/{{ $ads->id }}">{{ $ads->title }}</a></h6>
                    @if(!Auth::guest())
                        @if(Auth::user()->id == $ads->user_id)
                    <div class="row">
                        {!!Form::open(['action' => ['[email protected]', $ads->id], 'method' => 'POST',]) !!}
                            {{Form::hidden('_method', 'DELETE')}}
                            {{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
                        {!!Form::close() !!}
                        <a href="/ads/{{ $ads->id }}/edit" class="btn btn-primary mr-4">Edit</a>
                    </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', 'your post create .');
}

/**
 * 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', '[email protected]')->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

Please sign in or create an account to participate in this conversation.