webfuelcode

Member Since 2 Years Ago

Experience Points
13,740
Total
Experience

1,260 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
83
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 3
13,740 XP
Mar
29
2 weeks ago
Activity icon

Replied to How To Call Data From Two Different Model In A View

@silencebringer I tried it but it shows no result. I do not get the use of DB::raw in my case.

My table structure is below.

My Thread table is:

..........................................................................................................

| id | user_id | category_id | subject | slug | body | reported |

..........................................................................................................

My Comment table is:

...................................................................................................................................

| id | user_id | body | commentable_id | commanetable_type | reported |

...................................................................................................................................

Mar
27
3 weeks ago
Activity icon

Started a new Conversation How To Call Data From Two Different Model In A View

I have post reported page in admin dashboard. Trying to make a page where all reported post will be listed.

This is a forum project so thread, comment and reply can be reported. I have two model, Thread and Comment (for comments and replies).

Here I want to display latest 10 post from thread and comment reported in a single page.

Currently I have this function and do not get how to make it

public function reported()
    {
        $reported = Thread::where('reported', true)->latest()->paginate(10);
        $reportedcomments = Comment::where('reported', true)->latest()->paginate(10);
        $categories = Category::get();
        return view('admin.thread.reported', compact('reported', 'reportedcomments', 'categories'))->with('i', (request()->input('page', 1) - 1) * 10);
    }

How to make these appear in a limited number like 10 of all in a page and then the pagination. Not the 10 and 10, means total 20 from both models.

$reported = Thread::where('reported', true)->latest()->paginate(10);
$reportedcomments = Comment::where('reported', true)->latest()->paginate(10);
Activity icon

Awarded Best Reply on SQLSTATE[HY000]: General Error: 1364 Field 'username' Doesn't Have A Default Value

If someone find it...

The solution is in url. I don't exactly know what I did but it is solved now.

<form action="/follow/{{$user->username}}" method="post">
	//
</form>

In above I just add anther slash before the link.

Old follow/{{$user->username}} New /follow/{{$user->username}}

route

Route::post('follow/{user}', '[email protected]');
Activity icon

Started a new Conversation How To Call Reverse In Polymorphic

I am working on forum project. Just looking how to call thread slug by calling comments or reply.

Currently I can call:

@foreach($thread->comments as comment)
{{$comment->body}}

@foreach($comment->comments as reply)
{{$reply->body}}
@endforeach

@endforeach

I am trying to call thread slug from reply or comment.

Suppose a comment or reply is reported and admin need to see the thread post and user too. How can I make it to do so.

So the admin will hit the comment or reply link from the admin panel and he will redirected to thread page...

Here is comment.php

//
class Comment extends Model
{
    use CommentableTrait;

    protected $fillable=['body', 'user_id', 'comment_id'];
    //Get all of the owning commentable models.
    public function commentable()
    {
        return $this->morphTo();
    }

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

    public function likes()
    {
        return $this->hasMany(Like::class);
    }
}

CommentableTrait.php

<?php
/** Trait */

namespace App;

trait CommentableTrait
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->latest();
    }
    
    public function addComment($body)
    {
        $comment = new Comment();
        $comment->body=$body;
        $comment->user_id=auth()->user()->id;

        $this->comments()->save($comment);

        return $comment;
    }
}

Thread.php

//
//
class Thread extends Model
{
    use CommentableTrait, Sluggable;

    protected $fillable=['subject', 'slug', 'type', 'thread', 'user_id', 'category_id', 'solution'];

    public function getRouteKeyName()
    {
        return 'slug';
    }

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

    public function category()
    {
        return $this->belongsTo('App\category');
    }

    public function likes()
    {
        return $this->hasMany(Like::class);
    }
}
Mar
25
3 weeks ago
Activity icon

Started a new Conversation Followers And Following Separate Page

How can I make separate pages for followers and following from this lesson https://laracasts.com/series/laravel-6-from-scratch/episodes/58

Button on profile page will lead to list of user following by the user...

Activity icon

Started a new Conversation Undefined Variable

Undefined variable: thread

It shows the list when there are data but error when no posts are there.

@forelse($comments as $comment)
                              <h5>{{$user->name}} commented on <a href="{{route('thread.show',$thread->slug)}}">{{$comment->commentable->subject}}</a> <em>{{$comment->created_at->diffForHumans()}}</em></h5>
                          
                              @empty
                          <h5 class="text-muted">Oh! The comment area is very clean.</h5>
                          @endforelse
Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'username' Doesn't Have A Default Value

If someone find it...

The solution is in url. I don't exactly know what I did but it is solved now.

<form action="/follow/{{$user->username}}" method="post">
	//
</form>

In above I just add anther slash before the link.

Old follow/{{$user->username}} New /follow/{{$user->username}}

route

Route::post('follow/{user}', '[email protected]');
Mar
24
3 weeks ago
Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'username' Doesn't Have A Default Value

I am following Jeffry's lesson https://github.com/laracasts/Tweety/commit/36dc366e93776f7949357a49baa09da965fc8dc2

My controller for storing the ids:

public function store(User $user)
    {
        auth()->user()->toggleFollow($user);

        return back();
    }
Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'username' Doesn't Have A Default Value

Now the error is different.

How to set the route and form button.

<form action="{{route('userfollow'), $user->id)" method="post">
                  @csrf
                  <button type="submit" class="btn btn-info btn-sm">{{ auth()->user()->following($user) ? 'Unfollow me' : 'Follow me' }}</button>
                </form>

Route

Route::post('follow/{user}', '[email protected]')->name('userfollow');

Here in route Route::post('follow/{user}', '[email protected]')->name('userfollow'); show 404 error. And Route::post('follow', '[email protected]')->name('userfollow'); does not pass the user id, the erro is:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'following_user_id' cannot be null (SQL: insert into `follows` (`following_user_id`, `user_id`) values (?, 1))
Mar
23
3 weeks ago
Activity icon

Started a new Conversation SQLSTATE[HY000]: General Error: 1364 Field 'username' Doesn't Have A Default Value

Working on user follow and unfollow. Copied the lesson https://laracasts.com/series/laravel-6-from-scratch/episodes/62

Also, I made it to be used with username instead of name.

The error appears:

SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2021-03-23 14:55:28, 2021-03-23 14:55:28))

User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable, HasRoles, Followable;

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

    /**
     * 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 getRouteKeyName()
    {
        return 'username';
    }

    public function threads()
    {
        return $this->hasMany(Thread::class);
    }

    public function reputations()
    {
        return $this->hasMany(Reputation::class);
    }

    public function likes()
    {
        return $this->hasMany(Like::class);
    }
}

Followable.php

<?php

namespace App;

trait followable

{
	public function follow(User $user)
    {
        return $this->follows()->save($user);
    }
	
	public function unfollow(User $user)
    {
        return $this->follows()->detach($user);
    }

    public function toggleFollow(User $user)
    {
        // Tip: You can also use the toggle() method.
        //      We'll cover this in the next episode.
        //      $this->follows()->toggle($user);

        if ($this->following($user)) {
            return $this->unfollow($user);
        }

        return $this->follow($user);
    }

    public function following(User $user)
    {
        return $this->follows()
            ->where('following_user_id', $user->id)
            ->exists();
    }

    public function follows()
    {
        return $this->belongsToMany(User::class, 'follows', 'user_id', 'following_user_id');
    }
}

The form in view file

<form action="{{route('userfollow', $user->id)}}" method="post">
                  @csrf
                  <button type="submit" class="btn btn-info btn-sm">{{ auth()->user()->following($user) ? 'Unfollow me' : 'Follow me' }}</button>
                </form>

Route

Route::post('follow', '[email protected]')->name('userfollow');
Mar
20
4 weeks ago
Activity icon

Started a new Conversation How To Get Sum Of Two Variables [polymorphic]

Counting the total number of thread comments and replies.

Below is how I call the comments and replies.

{{--Answer/Comment--}}

        @foreach ($thread->comments as $comment)
        
        @include('thread.partials.comment-list')
        

        
            {{--Reply list--}}
            @foreach ($comment->comments as $reply)
                
                @include('thread.partials.reply-list')
                        
            @endforeach
            
        @endforeach

And I want the sum of comments and replies to display out of this div.

Mar
19
4 weeks ago
Activity icon

Started a new Conversation Checking The Thread Table If It Is Marked As Solved

Making the comment highlighted which is marked as solution. I am trying to create a variable in thread controller show method.

Thread table

| id | subject | body | solution |

Thread relation with comment is set and I can list comments. Question is here to create variable which can be used in view file to highlight the solution comment.

public function show(Thread $thread)
{
$comment = ?????
$solutioncheck = Thread::where(['solution'=>$comment->id]);
}

Getting error "id not defined" for $comment = $thread->comments;

Mar
18
4 weeks ago
Activity icon

Replied to If Else To Style In View File

@neilstee well its a button and I am using ajax. I tried a lot with ajax to change the button class when user click on it.

But no success. So I decided to look for laravel if-else in view or in the controller.

<form id="ajaxform">
                    <input type="hidden" name="id" value="{{$thread->id}}">
                    {{-- <input type="hidden" id="user_id" name="user_id" value="{{Auth::id()}}"> --}}
                    <button class="btn btn-secondary btn-sm save-data success"><i class="fas fa-thumbs-up"></i> {{$thread->favoritesCount()}}</button>
                </form>

And the ajax

$(".save-data").click(function(event){
        event.preventDefault();
  
        let id = $("input[name=id]").val();
        let _token   = $('meta[name="csrf-token"]').attr('content');
  
        $.ajax({
          url: "{{route('like')}}",
          type:"POST",
          data:{
            id:id,
            _token: _token
          },
          success:function(response){
            console.log(response);
            if(response) {
              $('.success').text(response.success);
              $("#ajaxform")[0].reset();
            }
          },
         });
    });
Activity icon

Started a new Conversation If Else To Style In View File

To decorate the view file, I am looking if-else statement.

Basically it is post like where user hit the button and the button turns to active. If not clicked it will appear as inactive. So trying to do it with if-else statement in the view side.

The button is inside <div>.

I do not want to make the view file with codes, so also looking if it can be done in controller side.

Mar
16
1 month ago
Activity icon

Started a new Conversation Sending Data To Controller Using Ajax

I am trying to do some tasks with ajax...one is here to send a data (post id) to the controller.

Final error I see is 500 error.

Nothing fancy in database just a pivot table which collects post and use id.

The button is:

<button id="button" class="btn btn-warning btn-sm" type="submit">Like {{$thread->likes->count()}}</button>
$(function(){
       $('#button').click(function() {
        var csrfToken='{{csrf_token()}}';
            $.ajax({
                url: '{{route('like')}}',
                type: 'POST',
                data: { id: 1, _token: csrfToken },
            });
       });
    });    
Mar
15
1 month ago
Activity icon

Started a new Conversation Adding Comment Id To Thread As Solution

Mark as solution, this is what I am trying to do with ajax. But no database entry in recorded.

Controller:

public function markAsSolution()
    {
        $solutionId = Request::get('solutionId');
        $threadId = Request::get('threadId');

        $thread = Thread::find($threadId);
        $thread->solution = $solutionId;
        if ($thread->save()) {
            if (request()->ajax()) {
                return response()->json(['status' => 'success', 'message' => 'marked as solution']);
            }
            return back()->withMessage('Marked as solution');
        }
    }

Route:

Route::post('/thread/mark-as-solution', '[email protected]')->name('markAsSolution');

View:

// Button for the action
<div  class="btn btn-success pull-right" onclick="markAsSolution('{{$thread->id}}','{{$comment->id}}',this)">Mark as solution</div>

// Script
<script>
    function markAsSolution(threadId, solutionId,elem) {
            var csrfToken='{{csrf_token()}}';
            $.post('{{route('markAsSolution')}}', {solutionId: solutionId, threadId: threadId,_token:csrfToken}, function (data) {
                $(elem).text('Solution');
            });
        }
</script>
Mar
11
1 month ago
Activity icon

Started a new Conversation Like Count With Vue Does Not Show

I am using vue js for like and dislike(remove like) and the number of total like counts. But the like count is not visible.

LikeComponent.vue

<template>
        <div class="">
                <a href="" @click.prevent="likeIt">
                    <small>{{ likeCount }}</small>
                    <i class="fa fa-thumbs-up" aria-hidden="true"></i>
                </a>
        </div>
</template>

<script>
    export default {
        data(){
            return {
                likeCount:0
            }
        },
        props:[
            'threadId','login','likes'
        ],
        created(){
            this.likeCount = this.likes
        },
        methods:{
            likeIt(){
                if (this.login) {
                    axios.post('/saveLike',{
                        id : this.threadId
                    })
                      .then(response => {
                        if (response.data == 'deleted') {
                            this.likeCount -= 1;
                        }else{
                            this.likeCount += 1;
                        }
                        // this.blog = response.data.data
                        // console.log(response);
                      })
                      .catch(function (error) {
                        console.log(error);
                      });
                }else{
                    window.location = 'login'
                }
            }
        }
    }
</script>

app.js


require('./bootstrap');

window.Vue = require('vue');



Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('like-component', require('./components/LikeComponent.vue').default);



const app = new Vue({
    el: '#app',
});

ThreadController

public function saveLike(Request $request)
    {
        $likecheck = Like::where(['user_id'=>Auth::id(),'thread_id'=>$request->id])->first();
        if($likecheck){
            Like::where(['user_id'=>Auth::id(),'thread_id'=>$request->id])->delete();
            return 'delete';
        }
        else{
            $like = new Like;
            $like->user_id = Auth::id();
            $like->thread_id = $request->id;
            $like->save();
        }
    }

route

Route::post('saveLike','[email protected]')

Thread single page

<like-component :thread-id="{{$thread->id}}" login="{{Auth::check()}}"></like-component>
Mar
09
1 month ago
Activity icon

Replied to Adding Data To Pivot Table

The function to enter the data.

I have post_id and user_id columns in the Like pivot table.

How to create the function to store the data in this table.

$like->thread_id = .................. $like->user_id = (here I can get the auth id)

I am not good at creating function and have not ever worked with pivot table.

Activity icon

Started a new Conversation Keeping My Custom Css With Vue Js

My question is about webpack.mix.js file where we have to run the npm run watch command which creates files in public folder.

Is this css file so important as I already have custom css on that project...

What should I do with the webpack.mix.js css file...

Mar
07
1 month ago
Activity icon

Started a new Conversation Adding Data To Pivot Table

I am working on Like pivot table. So the post id and user id will be saved.

The controller side I am not getting.

Mar
06
1 month ago
Activity icon

Started a new Conversation How To Make Relationship With Post And User In Like Table

Working on a project and stuck in like system. Currently, I am just using the route to understand.

I am stuck on creating relations between models. I have Post, User and Like tables.

So where to use "belongsTo", "hasMany", "manyToMany" or others...

I tried and even followed tutorials, but got errors.

Feb
21
1 month ago
Activity icon

Started a new Conversation Searching On Multiple Tables And Showing It In One Page

Couldn't make it happen smoothly. Please show me how can I use one search box for multiple database table searches.

Also, how to display "no result found..." if nothing matches on using a loop for two different variables.

Controller:

public function search(Request $request)
    {
        $this->validate($request, [
            'q' => 'required',
        ]);
        $threads = Thread::where('subject', 'like', '%' . $request->q . '%')->orWhere('thread', 'like', '%' . $request->q . '%')->paginate(20)->withQueryString();
        $users = User::where('name', 'like', '%' . $request->q . '%')->orWhere('email', 'like', '%' . $request->q . '%')->paginate(20)->withQueryString();
    
        return view('admin.contents.admin_search', compact('threads', 'users'));
    }

The result page is something like this:

@foreach($threads as $thread)
{
// Design for thread view
}
@endforeach

@foreach($users as $user)
{
//Design for user view
}
@endforeach
Feb
18
1 month ago
Activity icon

Started a new Conversation Trying To Trigger Modal From Bootstrap Dropdown

I have tried a lot but got no success. I even copied it https://stackoverflow.com/questions/56805836/trigger-modal-from-bootstrap-dropdown-menu

Below is my work where the button is an icon that is actually three dots.

Something different here in laravel?

<div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
                                  <a href="#" class="dropdown-item" data-toggle="modal" data-target="#edit{{$thread->id}}">Edit</a>
                                  <a href="#" class="dropdown-item" data-toggle="modal" data-target="#delete{{$thread->id}}">Delete</a>
                                  {{-- Edit modal --}}
                                  @include('admin.thread.modal.edit')
                                  {{-- Delete modal --}}
                                  @include('admin.thread.modal.delete')
                                </div>
Feb
06
2 months ago
Activity icon

Started a new Conversation Selected Sub-category In Edit View

Tring to show selected subcategory in a selection form.

@foreach ($categories as $category)
                                        <option value="{{ $category->id }}" disabled>{{ $category->name }} ----</option>
                                        @if ($category->children)
                                            @foreach ($category->children as $child)
                                                <option value="{{ $child->id }}">&nbsp;&nbsp;{{ $child->name }}</option>
                                            @endforeach
                                        @endif
                                    @endforeach
Feb
04
2 months ago
Activity icon

Started a new Conversation Changing The Style And Layout Of Laracasts/flash Modal

I am using laracasts/flash specially for overlay alerts. https://github.com/laracasts/flash

I want to change the default style of modal used by laracasts/flash. So where is the file I should go and edit or what is the other way to do this.

Things I want to change:

  1. Modal title appears on right and the cancel button just messed with the text.
  2. Modal size and the colors/bg colors.
Feb
02
2 months ago
Activity icon

Started a new Conversation How To Display Category Name Out Of The Loop

I am trying to get the category name as the title on top of the posts.

I have a left a section for categories and a right section for posts. The left section has the title "categories" so I just want to display the right section with the title which will be the selected category name.

forelse and foreach do it but the title is not inside forelse. What is the idea to get the category name as there is a category name or id in the URL already?

controller is :

public function show(Category $category)
    {
        $threads = Thread::where('category_id', $category->id)->get();
        return view('category.show', compact('threads'));
    }

view side :

@extends('layouts.front')

@section('content')
<div class="">
    <h2>????????????????????</h2>
    @forelse ($threads as $thread)
        <div class="card my-2">
            <div class="card-body">
                <a href="{{route('thread.show', $thread->id)}}">
                    <h4 class="card-title">{{ $thread->subject }}</h4>
                </a>
                    <p class="card-text">{{ str_limit($thread->thread,100) }}</p>
                    <p class="card-link">
                        Posted by: <a href="{{route('user_profile',$thread->user->name)}}">{{$thread->user->name}}</a> {{$thread->created_at->diffForHumans()}}
                        In: {{$thread->category->name}}
                    </p>
                
            </div>
        </div>
        
    @empty
            <h5>No categories are there</h5>
        
    @endforelse

    {{-- $thread->links() --}}
</div>
@endsection
Jan
31
2 months ago
Activity icon

Started a new Conversation Laravel Flash By Spatie

Can you provide the full steps of laravel flash by spatie? https://github.com/spatie/laravel-flash

I am not getting it...like controller side and package providers config/app/php

Jan
24
2 months ago
Activity icon

Replied to Post Image Not Found

How to set this so I can store the image in the correct place...

In filesystem.php

'my_files' => [
            'driver' => 'local',
            'root'   => public_path() . '/uploads',
        ],

What can I put in place of public_path() so the image path will store in the same place and I do not have to modify the rest of the codes on different pages?

Now it continuously storing the image under public' folder even though I have moved the public` folder to root. It creates one and stores it there.

Jan
23
2 months ago
Activity icon

Started a new Conversation Post Image Not Found

I uploaded the laravel project on shared hosting. But the images are not showing in the post.

The image address is not the correct path. trying to find this...

What I did to set the public folder?

  1. I simply copied .htaccess file from the public folder and pasted it in the root directory.
  2. Then I renamed the server.php file to index.php

So, what else should I fix to get the correct image path for the image I have saved or going to upload with the new posts, on publuc/uploads/imagename.png

Well, the project is working fine only the image path not correct.

Jan
16
3 months ago
Activity icon

Replied to Search Results Pagination Works Not

The view is:

@forelse ($posts as $post)
            <div class="card my-2">
                <div class="card-body">
                    <h5>
                        <a href="{{ route('post.show', $post->slug) }}">{{ $post->title }}</a>
                    </h5>
                    {!! Str::words($post->description, 25, '...') !!}
                </div>
            </div>
        @empty
            ..No result found..
        @endforelse

        {{ $posts->links() }}
Activity icon

Started a new Conversation Search Results Pagination Works Not

What is wrong here that the pagination does not work.

<form action="{{ route('search') }}" method="GET" role="search">
                            <div class="search">
                                <input type="text" class="form-control searchTerm" name="q" placeholder="What are you looking for?">
                                <button type="submit" class="searchButton">
                                    <i class="fa fa-search"></i>
                                </button>
                            </div>
                        </form>

Controller:

public function search(Request $request)
    {
        $this->validate($request, [
            'q' => 'required',
        ]);
        $posts = Post::where('title', 'like', '%' . $request->q . '%')->orWhere('description', 'like', '%' . $request->q . '%')->paginate(4);
    
        return view('pages.search', compact('posts'));
    }

Route:

Route::get('search', '[email protected]')->name('search');
Activity icon

Started a new Conversation Error On Uploading Some Images

What I see the error uploading some of the images...

Warning: POST Content-Length of 10452501 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Illuminate\Http\Exceptions\PostTooLargeException
Jan
12
3 months ago
Activity icon

Replied to How To Add Pagination In User's Posts

I am using @forelse ($user->posts as $post) so do not know how to call the paginate.

Also {{$post->links()}} does not work.

Activity icon

Started a new Conversation Trying To Show The Updated Posts

How to show the list of updated posts only with ascending order in laravel 7...

$updated = Post::latest('updated_at')->take(5)->get();

This line shows the updated as well as the newly created post list.

Activity icon

Started a new Conversation How To Add Pagination In User's Posts

@forelse ($user->posts as $post)
                    <div class="col-md-6 col-lg-4">
                        <div class="card mb-4">
                            @if (!empty($post->img1))
                                <img src="/uploads/post_img/{{ $post->img1 }}" class="card-img-top">
                            @endif
                            <div class="card-body">
                                <a href="{{ route('post.show', $post->slug) }}">{{ $post->title }}</a>
                            </div>
                        </div>
                    </div>
                @empty
                    <div class="card bg-secondary w-100 my-4">
                        <div class="card-body text-center text-light">
                            No posts records from {{ $user->name }}!
                        </div>
                    </div>
                @endforelse

Not sure about the controller

public function show($id)
    {
        $user = User::find($id);
        $posts = Post::paginate(6);
        return view('users.show', compact('user', 'posts'))->with('i', (request()->input('page', 1) - 1) * 6);
    }
Dec
18
3 months ago
Activity icon

Replied to Image Does Not Upload

I left enctype

Dec
17
4 months ago
Activity icon

Started a new Conversation Image Saves As Tmp

How to fix tmp filename saving to database...

I do not get why the database gets the tmp file name.

public function save_settings(Request $request, Admin $admin)
    {
        $admin = Admin::first();
        $admin->title = request('title');
        $admin->logo = request('logo');
        $admin->description = request('description');
        $admin->facebook = request('facebook');
        $admin->twitter = request('twitter');
        $admin->instagram = request('instagram');
        $admin->linkedin = request('linkedin');

        // Logo update and deleting from the storage
        if($request->hasFile('logo')){
            $filename = time() . '.' . $request->logo->getClientOriginalExtension();
            if($admin->logo){
                Storage::disk('my_files')->delete('classific_img/' . $admin->logo);
            }
            $request->logo->storeAs('classific_img', $filename, 'my_files');
            
            $admin->logo = $filename;
        }

        $admin->update($request->all());
        return redirect()->route('settings', compact('admin'))->withMessage('Site settings has updated successfully!');
}
Dec
16
4 months ago
Activity icon

Started a new Conversation Image Does Not Upload

I am trying to upload the logo. It saves the filename but does not upload...

Also, the file should be renamed but it saves as it is...

See the controller here"

public function save_settings(Request $request, Admin $admin)
    {
        $admin->title = request('title');
        $admin->logo = request('logo');
        $admin->description = request('description');
        $admin->facebook = request('facebook');
        $admin->twitter = request('twitter');
        $admin->instagram = request('instagram');
        $admin->linkedin = request('linkedin');

        // Logo update and deleting from the storage
        if($request->hasFile('logo')){
            $filename = time() . '.' . $request->logo->getClientOriginalExtension();
            if($admin->logo){
                Storage::disk('my_files')->delete('classific_img/' . $admin->logo);
            }
            $request->logo->storeAs('classific_img', $filename, 'my_files');
            
            $admin->logo = $filename;
        }

        $admin->update($request->all());
        return redirect()->route('settings', compact('admin'))->withMessage('Site settings has updated successfully!');
    }
Dec
14
4 months ago
Activity icon

Started a new Conversation Sending Message To The Owner Of The Post

I am trying to make a form for the message to the owner of the post. It is not user to user message.

So I am not sure if I should use package or a database is all for that. I thought a database and the auth can do.

The message system is like a classified website does...but I am not sure if it is a good idea...

Nov
24
4 months ago
Activity icon

Started a new Conversation Paginate For Posts Under Category

Trying to show the latest posts with pagination.

$subposts = Category::with(['posts', 'children.posts'])->where('id', $category->id)->first();

Tried get(), latest() but sometimes it says property does not found and sometimes collection error.

I have a page designed for subcategory and post list on two columns.

Nov
16
5 months ago
Activity icon

Started a new Conversation How To Loop In Controller For Multiple Files

I have tried different ways but not clear to me.

Basically, I am uploading two images with db column name img1, img2, so how to loop in the controller to avoid repeating the same code.

if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            if($post->img1){
                Storage::disk('my_files')->delete('post_img/' . $post->img1);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }

Above, for $post->img1 and $post->img2

Nov
14
5 months ago
Activity icon

Started a new Conversation If Condition In Controller For Multiple Variables

I am trying to upload two images for the post. And using the if statement for checking if the post has an older image.

So here, I am not sure how to use it. I think array would be in use in the place $post->img1.

Please correct it for two or more images.

            if($post->img1){
                Storage::disk('my_files')->delete('post_img/' . $post->img1);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }
Activity icon

Started a new Conversation How To Check And Delete Image From A Post On Updating

I am just trying to clear the storage by deleting unused images the post has, whenever the post is updated.

public function update(Request $request, Post $post)
    {
        $validated = $this->validate($request, [
            'title' => 'required',
            'img1' => 'sometimes|image',
            'category_id' => 'required',
            'description' => 'required'
        ]);

        // Post image upload
        if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            if(__________){
                Storage::disk('my_files')->delete('post_img/' . __________);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }

        $post->update($validated);
        return redirect()->route('post.show', $post->slug)->withMessage('Updated successfully!');
    }

Main part here is, I am not able to make it delete.

// Post image upload
        if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            if(_________){
                Storage::disk('my_files')->delete('post_img/' . _________);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }

if(__________){ Storage::disk('my_files')->delete('post_img/' . __________); } How to check if the post has an image file, and then delete it if the user uploads a new one.

Nov
13
5 months ago
Activity icon

Started a new Conversation Post With Image

Saving the post but not the image in the database. File upload works fine.

Please correct it to make the image save in the database.

controller:

public function store(Request $request)
    {
        $validatedData = $this->validate($request, [
            'title'         => 'required|min:3|max:255',
            'img1'         => 'sometimes|image',
            'img2'         => 'sometimes|image',
            'category_id'   => 'required|numeric',
            'description'   => 'required|min:10'
        ]);

        // Post image upload
        if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
/////////??????????/////////
        }
    
        $validatedData['user_id'] = Auth::id();
    
        $post = Post::create($validatedData);

        return redirect()->route('post.show', ['post' => $post->slug])->withMessage('Post created successfuly!');
    }
Nov
04
5 months ago
Activity icon

Replied to Get All Products From Parent Category And It's All Sub-categories

@amrsubzero I stuck in view page with relations.

How to show the subcategory name and its post title...?

Activity icon

Started a new Conversation Trying To Show Posts From Subcategory

I am trying to show the posts from subcategories, not collecting the posts to the parent category. Using the same table for both categories and subcategories.

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

    public function children()
    {
      return $this->hasMany('App\Category', 'parent_id');
    }

    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

How to make a function for the post view?

Nov
03
5 months ago
Activity icon

Awarded Best Reply on Display The 5 Sub Categories Of Parent Category

I got it. Just for someone who will need the same.

or, anyone can correct me if I am wrong. But it works for me.

The controller is below, which limits the 5 main categories.

public function posts()
    {
        $posts = Post::latest()->take(5)->get();
        $categories = Category::whereNull('parent_id')->with('children')->latest()->take(5)->get();
        return view('welcome', compact('posts', 'categories'));
    }

And view the page where I added the limitation to show 5 subcategories.

@forelse ($categories as $cat)
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h4>{{ $cat->name }}</h4>
                                <ul class="list-group list-group-flush">
                                    
                                    @foreach ($cat->children->take(5) as $child)
                                    <li class="list-group-item">
                                        {{ $child->name }} - {{ $child->posts->count() }}
                                    </li>
                                    @endforeach
                                    
                                </ul>
                        </div>
                    </div>
                </div>
            @endforelse

This is what I found. @foreach ($cat->children->take(5) as $child)

Activity icon

Replied to Display The 5 Sub Categories Of Parent Category

I got it. Just for someone who will need the same.

or, anyone can correct me if I am wrong. But it works for me.

The controller is below, which limits the 5 main categories.

public function posts()
    {
        $posts = Post::latest()->take(5)->get();
        $categories = Category::whereNull('parent_id')->with('children')->latest()->take(5)->get();
        return view('welcome', compact('posts', 'categories'));
    }

And view the page where I added the limitation to show 5 subcategories.

@forelse ($categories as $cat)
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h4>{{ $cat->name }}</h4>
                                <ul class="list-group list-group-flush">
                                    
                                    @foreach ($cat->children->take(5) as $child)
                                    <li class="list-group-item">
                                        {{ $child->name }} - {{ $child->posts->count() }}
                                    </li>
                                    @endforeach
                                    
                                </ul>
                        </div>
                    </div>
                </div>
            @endforelse

This is what I found. @foreach ($cat->children->take(5) as $child)