Lethal-Bacon
1 month ago
168
7
Laravel

Trying to get property 'id' of non-object

Posted 1 month ago by Lethal-Bacon

Alright im trying to make a relatively simple blog using laravel and i ran into some problems, fixing 1 error by 1 you get more and more new ones as some of you probably know...

From what testing i did, i can go into categories on the site, make new ones, edit them, delete them, in phpmyadmin categories table is populated and has an id and everything same thing with tags, everything works, issue started arising when i was making a new post and selecting a category, it said "column 'category_id' cannot be null" and "field 'category_id' doesn't have a default value".

So i thought it would be better if i posted my code relating to making new post and category related files for you pro's to see and tell/show me what is wrong and how to make it work as intended, thank you in advance to anyone trying to assist me with this.

create_post_table migration

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->text('content');
            $table->string('image')->nullable();
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
            $table->integer('category_id');
            $table->string('filename')->nullable();
            $table->string('mime')->nullable();
            $table->string('original_filename')->nullable();
        });
    }

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

create_categories_table migration

<?php

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

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

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

Post.php Provider

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
  use SoftDeletes;

  protected $fillable = [
 'title', 'description', 'content', 'category_id', 'image', 'published_at'
  ];

  public function category()
  {


    return $this->belongsTo(Category::class);
  }

  public function tags()
  
  {

    return $this->belongsToMany(Tag::class);

  }

 /**
  * check if post has  tags
  * @return bool
  */

 

 public function hasTag($tagId)
 {
    return in_array($tagId, $this->tags->pluck('id')->toArray());

 }
}

Category.php Provider

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
     protected $fillable = ['name'];

     public function posts()
     {

          return $this->hasMany(Post::class);
     }
}

PostController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\posts\CreatePostRequest;
use App\Http\Requests\posts\UpdatePostRequest;
use App\Post;
use App\Category;
use App\Tag;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class PostController extends Controller
{



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('posts.index')->with('posts', Post::all());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('posts.create')->with('categories', Category::all())->with('tags', Tag::all());

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreatePostRequest $request)
    {

        $image = $request->file('image');
        $extension = $image->getClientOriginalExtension();
        Storage::disk('public')->put($image->getFilename(). '.'.$extension, File::get($image));


        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->content = $request->content;
        $post->category_id = $request->category_id;
        $post->mime = $image->getClientMimeType();
        $post->original_filename = $image->getClientOriginalName();
        $post->filename = $image->getFilename().'.'.$extension;
        $post->save();

        if ($request->tags){
            $post->tags()->attach($request->tags);
        }

        session()->flash('success', 'Objava uspešno kreirana.');

        return redirect(route('posts.index'));
    }

    /**
     * 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(Post $post)
    {
        return view('posts.create')->with('post', $post)->with('categories', Category::all())->with('tags', Tag::all());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatePostRequest $request, Post $post)
    {
        $data = $request->only(['title', 'description', 'content']);
       
         if($request->tags){
        $post->tags()->sync($request->tags);

         }

        $post->update([
            'title' => $request->title,
            'description' => $request->description,
            'content' => $request->content
        ]);

        session()->flash('success', 'Objava uspešno promenjen.');

        return redirect(route('posts.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
           $post = Post::withTrashed()->where('id', $id)->firstOrFail();
        if($post->trashed()){

            $post->ForceDelete();
        }
        else{
            $post->delete();
        }

        session()->flash('success', 'Objava uspešno arhivirana');

        return redirect(route('posts.index'));
    }


    /**
     * Display a list of trashed posts
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function trashed()

    {

    $trashed = Post::onlyTrashed()->get();

return view('posts.index')->withPosts($trashed);
     
    }

     /**
     * Restore trashed post
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function restore($id)

    {
     $post = Post::withTrashed()->where('id', $id)->firstOrFail();
        $post->restore();

        session()->flash('success', 'Objava uspešno obnovljena.');

        return redirect()->back();
     
    }
}

CategoriesController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Http\Requests\Categories\CreateCategoryRequest;
use App\Http\Requests\Categories\UpdateCategoriesRequest;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('categories.index')->with('categories', Category::all());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
         return view('categories.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreateCategoryRequest $request)
    {


         Category::create([ 
             'name' => $request->name
         ]);
            
         session()->flash('success', 'Kategorija uspešno kreirana.');

         return redirect(route('categories.index'));
    }

    /**
     * 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(Category $category)
    {
         return view('categories.create')->with('category', $category);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateCategoriesRequest $request, Category $category)
    {
        $category->update([
            'name' => $request->name
        ]);
        $category->save();

        session()->flash('success', 'Kategorija uspešno promenjena.');

        return redirect(route('categories.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {

        $category->delete();

        session()->flash('success', 'Kategorija uspešno izbrisana.');

        return redirect(route('categories.index'));
    }
}

posts index.blade.php

@extends('layouts.app')

@section('content')

<div class="d-flex justify-content-end mb-2">

    <a href="{{ route('posts.create')  }}" class="btn btn-success">Dodaj Objavu</a>

</div>

<div class="card card-default">

    <div class="card-header">Objave</div>
    <div class="card-body">
        @if($posts->count()> 0)
        <table class="table">
            <thead>
                <th></th>
                <th>Naslov</th>
                <th>Kategorija</th>
                <th></th>
                <th></th>
            </thead>
            <tbody>
                @foreach($posts as $post)
                <tr>
                    <td>
                        <img src="{{  url('uploads/'.$post->filename) }}" width="120px" height="60px"
                            alt="{{$post->filename}}">
                    </td>
                    <td>
                        {{  $post->title  }}
                    </td>
                    <td>
                        <a href="{{  route('categories.edit', $post->category->id)  }}">
                            {{   $post->category->name    }}
                        </a>

                    </td>
                    @if($post->trashed())
                    <td>
                        <form action="{{route('restore-posts', $post->id)}}" method="POST">
                            @csrf
                            @method('PUT')
                            <button type="submit" class="btn btn-info btn-sm">Povrati</button>

                        </form>
                    </td>
                    @else(!$post->trashed())
                    <td>
                        <a href="{{route('posts.edit', $post->id)}}" class="btn btn-info btn-sm">Izmeni</a>
                    </td>
                    @endif
                    <td>
                        <form action=" {{ route('posts.destroy', $post->id)}}" method="POST">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger btn-sm">
                                {{  $post->trashed() ? 'Izbriši' : 'Arhiviraj' }}
                            </button>
                        </form>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
        @else
        <h3 class="text-center">Trenutno nema objava.</h3>
        @endif
    </div>

</div>

@endsection

posts create.blade.php

@extends('layouts.app')

@section('content')

<div class="card card-default">

    <div class="card card-header">
        {{  isset($post) ? 'Izmeni Objavu' : 'Kreiraj Objavu' }}
    </div>

    <div class="card card-body">
        @include('partials.errors')
        <form action="{{ isset($post) ?  route('posts.update', $post->id) : route('posts.store')  }}" method="POST"
            enctype="multipart/form-data">
            @csrf

            @if(isset($post))
            @method('PUT')
            @endif

            <div class="form-group">
                <label for="title">Naslov</label>
                <input type="text" class="form-control" name="title" id="title"
                    value="{{isset($post) ? $post->title :  ''  }}">

            </div>

            <div class="form-group">
                <label for="category">Kategorija</label>
                <select name="category" id="category" class="form-control">
                    @foreach($categories as $category)
                    <option value="{{$category->id}}" @if(isset($post)) @if($category->id === $post->category_id)
                        selected
                        @endif
                        @endif>
                        {{  $category->name   }}
                    </option>
                    @endforeach
                </select>
            </div>
            @if($tags->count() > 0)
            <div class="form-group">
                <label for="tags">Tagovi</label>


                <select name="tags" id="tags" class="form-control" multiple>
                    @foreach($tags as $tag)
                    <option value="{{ $tag->id  }}" @if(isset($post)) @if($post->hastag($tag->id))
                        selected
                        @endif
                        @endif>
                        {{  $tag->name   }}
                    </option>
                    @endforeach
                </select>
            </div>
            @endif

            <div class="form-group">
                <label for="description">Opis</label>
                <textarea name="description" id="description" cols="1" rows="2" class="form-control">
                {{isset($post) ? $post->description :  ''  }}
                </textarea>
            </div>

            <div class="form-group">
                <label for="content">Sadržaj</label>
                <textarea name="content" id="content" cols="5" rows="5" class="form-control">
                {{isset($post) ? $post->content :  ''  }}
                </textarea>
            </div>

            <div class="form-group">
                <label for="published_at">Objavljeno</label>
                <input type="text" class="form-control" name="published_at" id="published_at"
                    value="{{isset($post) ? $post->published_at :  ''  }}">

            </div>

            <div class="form-group">
                <label for="image">Slika</label>
                <input type="file" class="form-control" name="image" id="image"
                    value="{{isset($post) ? $post->image :  ''  }}">

            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-success">
                    {{  isset($post) ? 'Sacuvaj Promene'  : 'Kreiraj Objavu'  }}
                </button>
            </div>

        </form>

    </div>

</div>



@endsection

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