Update not working properly in my resource controller

Viewed 30

All functions are working in my resource controller, other than edit update.. data is coming in the edit page. but when I click on the update button. it do redirect to the posts page. data is updating in the database. but not showing it on the post page while using model. but when using query builder it is showing the data in the posts page but we can not edit it again. it says

Trying to get property 'id' of non-object (View: D:\Malaika\resourcecrudgen\resources\views\blog\edit.blade.php)  

that line is

<form action="{{ route('blogs.update', $data->id)}}" method="POST">

andsometimes it says page not found, i literally dont know whats going on.If You guys can help I'll be thankful.

Blog.Controller:

<?php

namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use DB;
use validate;
class BlogController extends Controller
{
   
  public function index()
    {
        
        $data = DB::table('blogs')->where("is_active" , 1)->where("is_deleted" , 0)->get();
        return view('blog.index',compact('data'));
    }

  
    public function create()
    {
       return view('blog.create');
    }

   
    public function store(Request $request)
    {
    
       $data = new Blog;
       $data->user_id = Auth::id();
       $data->username = $request->input('username');
       $data->email = $request->input('email');
       $data->save();
       return redirect()->back()->with('status','Record was created succesfully');
    }

    public function show($id)
    {
        
    }

    public function edit($id)
    {   

      $data=Blog::find($id);
      
      return view('blog.edit',compact('data'));
    }

    public function update(Request $request, $id)
    {
    
        $validatedData = $request->validate([
         
            'username' => 'required|max:255',
            'email' => 'required'
        ]);
        Blog::whereId($id)->update($validatedData);
        return redirect('blogs')->with('status', 'Record is successfully updated');
    }

    public function destroy($id)
    {

       $data = Blog::find($id);
         $data->is_active = 0;
        $data->is_deleted = 1;
        $data->save();
       $data->delete();
       return redirect()->back()->with('status','Record was deleted Successfully');

    }
}

Blog.php(The Model)

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    class Blog extends Model
    {
        use HasFactory,SoftDeletes;
        protected $table = 'blogs';
        protected $fillable = [
            'user_id',
            'username',
            'email',
        ];
    
        public function users() {
    
            return $this->belongsTo(User::class, 'user_id', 'id');
        }
    
    
    
         protected $dates = ['deleted_at'];
    }


index.blade.php

@extends('layouts.frontend')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                   Records
                    <a href="{{url('blogs/create')}}" class="btn btn-primary float-end">Add a Record</a>
                </div>

                <div class="card-body">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                           @foreach($data as $p)
                                <th>{{$p->id}}</th>
                                <th>{{$p->user_id}}</th>
                                <th>{{$p->username}}</th>
                                <th>{{$p->email}}</th>
                                <th><a href="{{ route('blogs.edit', $p->id)}}" class="btn btn-primary">Edit</a></th>
                                <th>
                                <form action="{{url('blogs/'.$p->id)}}" method="POST">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-danger">DELETE</button>
                                <!-- <th><a href="{{url('posts/'.$p->id)}}" class="btn btn-warning">Delete</a></th> -->
                                </form>
                                </th>
                                </tr>
                        </tbody>
                        @endforeach
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Edit.blade.php

@extends('layouts.frontend')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
@if(session('status'))
<div class="alert alert-success">{{session('status')}}</div>
@endif
            <div class="card">
                <div class="card-header">
                    <h4>Edit Records</h4>
                    <a href="{{url('blogs')}}" class="btn btn-danger float-end">Back</a>
                </div>

                <div class="card-body">
                    <form action="{{ route('blogs.update', $data->id)}}" method="POST">
                        @csrf
                        @method('PATCH')
                        
                        <input type="hidden" name="id" value="{{$data->id}}">
                        <div class="form-group mb-3">
                            <label for="">User Name</label>
                            <input type="text" name="username" class="form-control" value="{{$data->username}}">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Email</label>
                            <input type="email" name="email" class="form-control" value="{{$data->email}}">
                        </div>
                            <div class="form-group mb-3">
                            <button type="submit" name="submit" id="submit">Update</button>
                        </div>

                    </form>
            </div>
        </div>
    </div>
</div>
@endsection

Web.php:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;
use App\Http\Controllers\PagesController;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('home');
});

Route::get('/','App\Http\Controllers\PagesController@index');
Route::get('/about','App\Http\Controllers\PagesController@about');
Route::get('/users/{id}/{cop}','App\Http\Controllers\PagesController@users');


Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::middleware(['auth'])->group(function(){
    Route::resource('blogs', BlogController::class);    
});

Blogs Migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
             $table->integer('user_id');
            $table->string('username');
            $table->string('email');
            $table->integer('is_active')->default(1);
            $table->integer('is_deleted')->default(0);
            $table->timestamp('deleted_at');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}
0 Answers
Related