Robinmvdoorn

Member Since 3 Years Ago

Rotterdam

Experience Points
7,560
Total
Experience

2,440 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
67
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.

  • Community Pillar

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

Level 2
7,560 XP
Dec
11
2 months ago
Activity icon

Replied to If A User Liked 3 Books It Can Comment

I did this to get what i want:

User.php:

public function getCanCommentAttribute(): bool
{
    return $this->favorites()->count() >= 3;    
}

in my view:

@if(auth()->user()->can_comment)
    <!-- show form -->
@else
    <p>You must favorite at least 3 books before you can place a comment.</p>
@endif
Dec
10
2 months ago
Activity icon

Started a new Conversation If A User Liked 3 Books It Can Comment

Hello, I am making a site where users can like books and also comment on them. I want the user to be able to comment only if it has liked at least 3 books. How can I implement this?

What is this kind of validation called because I am having a hard time searching for solutions.

Thanks!

This is how my code is build up:

User Model:

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'role',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function favorites()
    {
        return $this->belongsToMany(Book::class, 'favorites')
            ->using(Favorite::class)
            ->withTimestamps()
            ->as('favorites');
    }
}

User Controller:

class UserController extends Controller
{
    public function favorites(Request $request)
    {
        $books = $request->user()->favorites()->latest()->get();

        return true;
    }

}

Comment Model:

class Comment extends Model
{
    protected $fillable = ['body', 'book_id', 'user_id'];

    public function book()
    {
        return $this->belongsTo(Book::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function parent()
    {
        return $this->belongsTo(Comment::class, 'parent_id');
    }
}

Comment Controller:

class CommentsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request, Book $book)
    {
        $validated = $request->validate([
            'body' => 'required',
        ]);

        $book->comments()->create([
            'user_id' => auth()->id(),
            'body' => $validated['body'],
        ]);

        return back();
    }
}

Favorite Model:

class Favorite extends Pivot
{
    protected $table = 'favorites';

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function book()
    {
        return $this->belongsTo(Book::class);
    }
}

Favorite Controller:

class FavoritesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        $favorites = $user->favorites()
            ->orderByDesc('favorites.created_at')
            ->paginate(10);

        return view('books.favorites', ['favorites' => $favorites]);
    }

    public function update(Book $book)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        if ($user->favorites()->where('book_id', $book->id)->exists()) {
            return redirect()->back()
                ->with('error', 'This item is already in your favorites!');
        }
        $user->favorites()->attach($book);

        return redirect()->back()
            ->with('success', 'Book, ' . $book->title . ' Added to your reading list.');
    }

    public function destroy(Book $book)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        $user->favorites()->detach($book);

        return redirect()->back()
            ->with('success', 'Book removed from favorites');
    }
}

show.blade.php :

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="my-3">
            <a class="btn btn-secondary" href="{{ route('books.index') }}">
                terug
            </a>
        </div>

        <div class="row my-3">
            <div class="col-lg">
                <img src="{{ $book->image }}" alt="{{ $book->title }}">
            </div>

            <div class="col-lg">
                <header>
                    @if($book)
                        <h1>{{$book['title']}}</h1>
                    @else
                        <h1>{{$error}}</h1>
                    @endif
                </header>

                <p>{{$book['author']}}</p>
                <p>{{$book['description']}}</p>


                @if($isFavorite)
                    <form method="POST" action="{{ route('favorites.destroy', ['book' => $book]) }}">
                        @csrf
                        @method('DELETE')

                        <button type="submit" class="btn btn-danger btn-block">Unfavorite</button>
                    </form>
                @else
                    <form method="POST" action="{{ route('favorites.update', ['book' => $book]) }}">
                        @csrf
                        @method('PUT')

                        <button type="submit" class="btn btn-primary btn-block">Voeg toe aan leeslijst</button>
                    </form>
                @endif

                @can('admin')
                    <a class="btn btn-secondary btn-block mt-2" href="{{ route('books.edit',$book->id) }}">
                        Edit
                    </a>

                    <form class="mt-2" action="{{ route('books.destroy', $book->id)}}" method="POST"
                          onsubmit="return confirm('Are you sure?')">
                        @csrf
                        @method('DELETE')
                        <button class="btn btn-danger btn-block" type="submit">Delete</button>
                    </form>
                @endcan
            </div>
        </div>

        <hr>

        @if($book->comments->isNotEmpty())
            <div class="card mb-3">
                <ul class="list-group list-group-flush">
                    @foreach ($book->comments as $comment)
                        <li class="list-group-item">
                            <p class="card-text">{{ $comment->body }}</p>

                            <p class="m-0 card-text small text-muted">
                                {{ $comment->created_at->toFormattedDateString() }}
                                &bull;
                                {{ $comment->user->name }}
                            </p>
                        </li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form method="POST" action="{{ route('books.comments.store', ['book' => $book]) }}" method="POST">
            @csrf
            <div class="form-group">
                <input placeholder="your comment here." type="text" class="form-control" id="body" name="body"/>
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-block">Comment</button>
            </div>
        </form>
    </div>
@endsection

Nov
26
3 months ago
Activity icon

Replied to Favorites Don't Get Saved

Would really appreciate that, thanks!

Activity icon

Replied to Favorites Don't Get Saved

Yes, thank you for looking at my GitHub repo! This is a project for school and i'm still a beginner. I really appreciate all the help! :)

Activity icon

Replied to Favorites Don't Get Saved

I applied this and now it works!

I still need to perfect it because I still can't unfavourite a book by clicking the favorite button again. And I also need to give some feedback on the buttons. I'm going to watch the tutorial you recommended.

Thank you very much for your help!

Nov
24
3 months ago
Activity icon

Started a new Conversation Favorites Don't Get Saved

Hello, I wan users to be able to favorite a book. But when i click the favorite button (submit btn) I get this error:

syntax error, unexpected 'public' (T_PUBLIC)

or when i remove the show function form FavoritesController I get the error:

Call to a member function count() on null

This is what i made...

favorites migration:

Schema::create('favorites', function (Blueprint $table) {
            $table->increments('id');
            $table->foreignId('user_id')->constrained('users');
            $table->foreignId('book_id')->constrained('books');
            $table->timestamps();
        });

Favorite.php:

class Favorite extends Model
{
    protected $table = "favorites";

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function book(){
        return $this->belongsTo(Book::class);
    }

}

in User.php:

public function favorite(){
        return $this->hasMany(Favorite::class);
    }

in Book.php:

public function favorite(){
        return $this->hasMany(Favorite::class);
    }

route in web.php:

Route::resource('/favorite', FavoriteController::class);

In FavoritesController: (the 'if' in the store function to prevent duplicate favorites does not work yet...)

public function __construct() {
        $this->middleware(['auth']);
    }

public function index()
    {
        $user = Auth::user();
        $favorites = Favorite::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);

        return view('books.favorite', compact('user', 'favorites'));
    }

    
 public function store(Request $request)
    {
        //Validating title & body field
        $this->validate($request, array(
            'user_id'=>'required',
            'book_id'=>'required',
        ));

        $status=Favorite::where('user_id',Auth::user()->id)
            ->where('book_id',$request->book_id)
            ->first();

//        if(isset($status->user_id) and isset($request->book_id))
//        {
//            return redirect()->back()->with('flash_messaged', 'This item is already in your
//       favorites!');
//        }
//        else
//        {
        $favorite = new Favorite;

        $favorite->user_id = $request->user_id;
        $favorite->book_id = $request->book_id;
        $favorite->save();

        return redirect()->back()->with('success',
        'Book, '. $favorite->book->title. ' Added to your reading list.');

    }

public function destroy($id)
    {
        $favorite = Favorite::findOrFail($id);
        $favorite-> delete();

        return redirect()->route('favorite.index')
            ->with('success', "book deleted from favorites");
    }

in my index.blade.php:

@foreach($books as $book)

                @if ($book->status === 0)
                <div class="col-md-3 card border-9 text-center m-1 p-2">
                @else
                <div class="d-none">
                @endif
                    <img src="{{$book->image}}" alt="{{$book->title}}" class="card-img">
                    <h2 class="card-title">{{$book->title}}</h2>
                    <p class="card-text">{{$book->author}}</p>
                    <p class="card-text">{{$book->category->title}}</p>
                    <a  class="btn btn-light m-1" href="{{route('books.show', $book->id)}}">Lees meer</a>
                    <form action="{{route('favorite.store')}}" id="contact_form" method="post">
                        {{csrf_field()}}
                        <input name="user_id" type="hidden" value="{{Auth::user()->id}}" />
                        <input name="product_id" type="hidden" value="{{$book->id}}" />
                        <button type="submit" class="btn btn-primary btn-block">Favoriet</button>
                    </form>
                </div>
            @endforeach

In favorite.blade.php:

@section('content')

    @if (Auth::user()->favorites->count() )
        @foreach ($favorites as $favorite)
            {{$favorite->book->title}}
        @endforeach
    @endif

@endsection

If anyone sees what I did wrong please let me know!

Nov
15
3 months ago
Activity icon

Started a new Conversation Route Not Defined

I want to route to my panel.blade.php but it says it is not defined, what did i do wrong?

web.php:

Route::get('/panel', [BooksController::class, 'panel'])->name('panel');

BooksController.php

public function panel()
    {
        $books = Book::orderBy('created_at', 'desc')->get();
        $categories = Category::all();

        return view('books.panel', compact('books', 'categories'));
    }

app.blade.php (blade with navigation part):

 <a  class="nav-a m-3 p-2" href="{{route('books.panel')}}">Panel</a>

What did I forget or do wrong?

Nov
09
3 months ago
Activity icon

Replied to What Is Wrong With My Edit Function/form?

Copied this and now it is working! Thank you so much!

Activity icon

Replied to What Is Wrong With My Edit Function/form?

Thank you for your reply. I now get redirected to the index page and see the succes message. but the changes I made are not applied.

Nov
08
3 months ago
Activity icon

Replied to What Is Wrong With My Edit Function/form?

When I click on the submit button I don't get redirected to the index blade. And i really don't get why.

Activity icon

Replied to What Is Wrong With My Edit Function/form?

Yes, still does nothing when i click the button in the edit form.

my resource route is:

Route::resource('books', BooksController::class);
Activity icon

Replied to What Is Wrong With My Edit Function/form?

I get this for update:

Method: PUT|PATCH, URI: books/{book}, Name: books.update, Action: App\Http\Controllers\[email protected], Middleware: web

Activity icon

Replied to What Is Wrong With My Edit Function/form?

Thank you for your reply, I tried this but it is still not working for me unfortunately.

Activity icon

Replied to What Is Wrong With My Edit Function/form?

I check this but don't see anything.

Activity icon

Replied to What Is Wrong With My Edit Function/form?

Yes i changed my redirect to:

return redirect()->route('books.index');
Activity icon

Replied to What Is Wrong With My Edit Function/form?

Tried this but still does not work.

Activity icon

Replied to What Is Wrong With My Edit Function/form?

I don't get an error but stay on the page after clicking the submit button. And the changes are not applied. So i don't know what i missed.

Activity icon

Replied to What Is Wrong With My Edit Function/form?

Thank you,

I use this for routes:

Route::get('/', [BooksController::class, 'index'])->name('books');

Route::resources(['books' => BooksController::class]);
Activity icon

Started a new Conversation What Is Wrong With My Edit Function/form?

Hello i'm trying to get the edit function in my project working. I can't figure out what I did wrong or left out?

My edit + update function in the controller:

public function edit($id)
    {
        $book = Book::find($id);
        return view('books.edit', compact('book'));
    }

public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required',
            'author' => 'required',
            'description' => 'required',
            'image' => 'required',
            'category' => ['exists:categories,id'],
        ]);

        $books = Book::find($id);
        $books->title = $request->get('title');
        $books->author = $request->get('author');
        $books->description = $request->get('description');
        $books->image = $request->get('image');
        $books->category_id = $request->get('category');
        $books->save();

        return redirect(route('.books'));
    }

my edit blade:

<div class="container">
        <form method="post" action="{{route('books.update', $book->id)}}">
            @csrf
            @method('PATCH')
            <div class="form-group">
                <label for="category">Category</label>
                <select class="form-control" name="category" id="category">
                    <option {{$book->category->title == 'Biografie' ? 'selected': ''}}>Biografie</option>
                    <option {{$book->category->title == 'Drama' ? 'selected': ''}}>Drama</option>
                    <option {{$book->category->title == 'Proza' ? 'selected': ''}}>Proza</option>
                    <option {{$book->category->title == 'Non-fictie' ? 'selected': ''}}>Non-fictie</option>
                    <option {{$book->category->title == 'Media' ? 'selected': ''}}>Media</option>
                </select>
            </div>
            <div class="form-group">
                <label for="title">Title</label>
                <input type="text" class="form-control" id="title" name="title" value="{{$book->title}}">
                @if ($errors->has('title'))
                    <span class="alert">{{$errors->first('title')}}</span>
                @endif
            </div>
            <div class="form-group">
                <label for="author">Author</label>
                <input type="text" class="form-control" id="author" name="author" value="{{$book->author}}">
                @if ($errors->has('author'))
                    <span class="alert">{{$errors->first('author')}}</span>
                @endif
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <input type="text" class="form-control" id="description" name="description" value="{{$book->description}}">
                @if ($errors->has('description'))
                    <span class="alert">{{$errors->first('description')}}</span>
                @endif
            </div>
            <div class="form-group">
                <label for="image">Image</label>
                <input type="text" class="form-control" id="image" name="image" value="{{$book->image}}">
            </div>
            <button type="submit" class="btn-primary btn-block">Save changes</button>
        </form>
    </div>

Nov
07
3 months ago
Activity icon

Replied to Data In Blade From Foreign Id

Thank you for your advice, i will use this. :)

Activity icon

Replied to Data In Blade From Foreign Id

Thank you! I changed my code to your suggestion.

Activity icon

Started a new Conversation Data In Blade From Foreign Id

Hello, I have a site with Books and the Books have categories. Now I want to display the category of the book in my index.blade.

But i think because it is a foreign Id i get:

"{"id":1,"title":"Biografie","created_at":null,"updated_at":null}"

instead of just:

"Biografie"

How do i display only the title form the category in the blade?

My blade:

 @foreach($books as $book)
                <div class="col-md-3 card border-9 text-center m-1 p-2">
                    <img src="{{$book['image']}}" alt="{{$book['title']}}" class="card-img">
                    <h2 class="card-title">{{$book['title']}}</h2>
                    <p class="card-text">{{$book['author']}}</p>
                    <p class="card-text">{{$book['category']}}</p>
                    <a  class="btn btn-light m-1" href="{{route('books.show', $book['id'])}}">Lees meer</a>
                    <a  class="btn btn-light m-1" href="#">Voeg toe aan leeslijst</a>
                </div>
            @endforeach
Oct
29
4 months ago
Activity icon

Replied to Route Not Defined.

This worked for me, thank you!

Activity icon

Replied to Route Not Defined.

All my routes:

Route::get('/', [BooksController::class, 'index'])->name('books');
Route::get('/books', [BooksController::class, 'index'])->name('books');
Route::get('books/create', [BooksController::class, 'create'])->name('books.create')->middleware('auth','admin');
Route::post('books/store', [BooksController::class, 'store'])->name('books.store');
Route::get('books/{id}', [BooksController::class, 'show'])->name('books.show');
Route::get('books/{id}/edit', [BooksController::class, 'edit'])->name('books.edit');
Route::patch('books/{id}', [BooksController::class, 'update'])->name('books.update');
Route::get('books/{id}', [BooksController::class, 'destroy'])->name('books.destroy');

Route::post('/books/{book}/comments', [CommentsController::class, 'store'])->name('comments.store');

Route::get('/home', [BooksController::class, 'index'])->name('home');
Activity icon

Started a new Conversation Route Not Defined.

I get the error:

Route [books.show] not defined.

Route in web.php:

Route::get('books/{id}', [BooksController::class, 'show'])->name('books.show');

In BookController.php:

 public function show($id)
    {
        $book = Book::find($id);
        if ($book === null) {
            abort(404, "No book has been found.");
        }

        return view('books.show', compact('book'));
    }

link in index.blade.php:

<a  class="btn btn-light m-1" href="{{route('books.show', $book['id'])}}">Read more</a>

About an hour ago this was all still working. I added some functions to the bookController.php (like the update and delete function) and then it stopped working and gives me this error now.

When i type in the url (ex: http://website.test/books/1) i get a blank page.

Does anyone know what i did wrong?

Activity icon

Replied to How To Hide Parts Of Your View For Users With Different Roles?

This is exactly what i was looking for, thank you!

Activity icon

Started a new Conversation How To Hide Parts Of Your View For Users With Different Roles?

I have a navigation with links and ik want to only show the 'add a book' link to users with the role of admin.

How can i do this in my view using something like this?

view:

@if(Auth::user()->role == "admin")
 <a  class="nav-a m-3" href="{{route('books.create')}}">Add a book</a>
@endif

user migration:

Schema::create('users', function (Blueprint $table) {
 	$table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('role');
        $table->rememberToken();
        $table->timestamps();
});
Oct
23
4 months ago
Activity icon

Replied to Comments Don't Get Id From Corresponding Post.

Yes this was it, thank you so much!

Edited my Comment Model to

class Comment extends Model
{

    protected $fillable = ['body', 'book_id'];

    public function book()
    {
        return $this->belongsTo(Book::class);
    }
}

Activity icon

Started a new Conversation Comments Don't Get Id From Corresponding Post.

I want to make a platform with book and users can comment on the books. Tried to follow the tutorials form Laravel 5.4 on this. But i get this error:

SQLSTATE[HY000]: General error: 1364 Field 'book_id' doesn't have a default value (SQL: insert into `comments` (`body`, `updated_at`, `created_at`) values (test, 2020-10-23 14:53:35, 2020-10-23 14:53:35))"

i also want to add these who commented but want to add that later.

This is what i have:

Migration for comments:

public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->integer('book_id');
            $table->text('body');
            $table->timestamps();
        });
    }

In Comment Model:

public function book()
    {
        return $this->belongsTo(Book::class);
    }

In CommentController:

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


public function store(Book $book)
    {

        Comment::create([

            'body' => request('body'),
            'book_id' => $book->id
            //'user_id' => auth()->id()
        ]);

        return back();
    }

In web.php

Route::post('/books/{book}/comments', [CommentsController::class, 'store'])->name('comments.store');

In the form where you can add a comment (located in book/show.blade.php):

    <div class="container">
        <div>
            <form method="POST" action="/books/{{ $book->id }}/comments">
                @csrf
                <div class="form-group">
                    <input placeholder="your comment here." type="text" class="form-control" id="body" name="body"/>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn-primary btn-block">Comment</button>
                </div>
                <input type="hidden" name="book_id" value="{{$book->id}}">
            </form>
        </div>
    </div>

Anyone know what i did wrong and why the book_id is not filled?