Lethal-Bacon

Lethal-Bacon

Member Since 1 Month Ago

Experience Points
80
Total
Experience

4,920 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
80 XP
Aug
08
1 month ago
Activity icon

Replied to Trying To Get Property 'id' Of Non-object

Awesome, thank you for clarifying what was actually wrong, huge thanks, now all seems to work as intended.

Activity icon

Replied to Trying To Get Property 'id' Of Non-object

Alright, thanks, so now i have 2 categories, and 2 tags created, when i click posts it says no posts currently in my native language, which is now fine as i deleted a failed test post from the database.

now when i go and click add new post, populate all fields and select laravel as 2nd option from the categories select, upon clicking publish i get this

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category' in 'field list' (SQL: insert into `posts` (`title`, `description`, `content`, `category`, `mime`, `original_filename`, `filename`, `updated_at`, `created_at`) values (test, test, test, 2, image/jpeg, learn-php.jpg, phpAF0D.tmp.jpg, 2020-08-08 13:25:20, 2020-08-08 13:25:20))

i sense that "category" part relates to "2" part which should be the id of the category

Activity icon

Replied to Trying To Get Property 'id' Of Non-object

i have changed the PostController line you mentioned to

$post->category = $request->category;

Error is pointing me to this line in posts/index.blade.php

<a href="{{  route('categories.edit', $post->category->id)  }}">
Activity icon

Started a new Conversation Trying To Get Property 'id' Of Non-object

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