nickywan123

Member Since 1 Year Ago

Experience Points
13,240
Total
Experience

1,760 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
3
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,240 XP
Apr
15
2 days ago
Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::links Does Not Exist

My bad, I didn't see your edited 2nd reply. How come if I paginate my index() threads 10 per page, it means I have to paginate 10 for search() as well?

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::links Does Not Exist

I think it shows paginator:

Illuminate\Pagination\LengthAwarePaginator {#1492 ▼
  #total: 26
  #lastPage: 3
  #items: Illuminate\Database\Eloquent\Collection {#1479 ▶}
  #perPage: 10
  #currentPage: 1
  #path: "http://forum.test/threads"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

I have a separate controller to handle the searching:

class SearchController extends Controller
{
    public function search(Request $request){
       
        $threads = Thread::search($request->input('search'))->get();
       

        return view('threads.index',compact('threads'));

    }
}

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::links Does Not Exist

It shows:

#items: Illuminate\Database\Eloquent\Collection {#1479 ▼
    #items: array:10 [▼
      0 => App\Thread {#1467 ▶}
      1 => App\Thread {#1466 ▶}
      2 => App\Thread {#1465 ▶}
      3 => App\Thread {#1464 ▶}
      4 => App\Thread {#1463 ▶}
      5 => App\Thread {#1462 ▶}
      6 => App\Thread {#1461 ▶}
      7 => App\Thread {#1460 ▶}
      8 => App\Thread {#1459 ▶}
      9 => App\Thread {#1458 ▶}
    ]
  }

I mean the issue only happens when I try to use the search function.

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::links Does Not Exist

This is my thread controller:

 public function index(Channel $channel, ThreadFilters $filters)
    {

        $threads = Thread::latest()->filter($filters);

        if($channel->exists){
            $threads->where('channel_id',$channel->id);
        }

        $threads = $threads->paginate(10);
        
        return view('threads.index',compact('threads'));
    }
Activity icon

Started a new Conversation Method Illuminate\Database\Eloquent\Collection::links Does Not Exist

I implemented laravel scout(aglolia) for search indexing for my posts.

So in my index I have something like below:

 <div class="col-md-8">
            @forelse($threads as $thread)
            <div class="card mb-3">
                <div class="card-header">
                    <div class="level">
                        <h4 class="flex">   
                        <img src="{{asset('/images/uploads/threads/images/'.($thread->image ?? 'default-post-img.png'))}}"  height="60" width="60" alt="image">     
                         <a href="{{$thread->path()}}" style="text-decoration: none;">{{$thread->title}}</a>
                        </h4>
                        <a href="{{$thread->path()}}">{{$thread->replies_count}} {{Str::plural('reply',$thread->replies_count)}}</a>
                    </div>
                </div>
            </div>
            @empty
                <p>There are no threads at the moment.</p>
            @endforelse
            {{ $threads->links() }}

Now, the search function works normally but I added pagination to my threads and tried using the search function but it doesn't work and says:

Method Illuminate\Database\Eloquent\Collection::links does not exist

how do I fix this if I want to use paginate?

Activity icon

Replied to How To Upload Video?

Well this is how my form looks like:

 <div class="card">
                <div class="card-header">Create a new thread.</div>
                <ul class="nav nav-tabs mt-1">
                    <li class="nav-item">
                        <a href="" data-target="#post" data-toggle="tab" class="nav-link {{ count($errors)|| Session::has('error-image') ? '' : 'active'}} ">Post</a>
                    </li>               
                    <li class="nav-item">
                        <a href="" data-target="#image" data-toggle="tab" class="nav-link {{ $errors->has('image')||Session::has('error-image') ? 'active' : ''}}">Image & Video</a>
                    </li>
        
                </ul>
             <div class="tab-content">
                <!-- Post tab -->
                <div class="tab-pane card-body mt-1 {{count($errors) || Session::has('error-image') ? '' : 'active'}}" id="post">
                    <form method="POST" action="/threads">
                        @csrf
                        <div class="form-group" >
                            <input type="hidden" name="post" value="post">
                            <label for="channel_id">Select A Channel:</label>
                            <select name="channel_id" id="channel_id" class="form-control @error('channel_id') is-invalid @enderror" required>
                                <option value="">Choose one.....</option>
                                @foreach($channels as $channel)
                                 <option value="{{$channel->id}}" {{old('channel_id') == $channel->id ? 'selected' : ''}}>
                                    {{$channel->name}}</option>
                                @endforeach
                            </select>
                        </div>
                        @error('channel_id')
                        <div class="alert alert-danger">{{ $message }}</div>
                        @enderror
                        <div class="form-group">
                            <label for="title">Title:</label>
                            <input type="title" name="title" class="form-control @error('title') is-invalid @enderror" id="title" placeholder="Title" value="{{old('title')}}" required>
                        </div>
                        @error('title')
                        <div class="alert alert-danger">{{ $message }}</div>
                        @enderror
                        <div class="form-group">
                            <label for="body">Body</label>
                            <textarea class="form-control @error('body') is-invalid @enderror" id="body" name="body" rows="8" placeholder="Enter your text" required >{{old('body')}}</textarea>
                        </div>
                        @error('body')
                        <div class="alert alert-danger">{{ $message }}</div>
                        @enderror
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">Publish</button>
                        </div>
    
                    </form>
                </div>
                <!--Upload image/video tab -->
                 <div class="tab-pane card-body mt-1 {{ $errors->has('image') || Session::has('error-image') ? 'active' : ''}}" id="image">
                    <form method="POST" enctype="multipart/form-data" action="/threads">
                        @csrf
                        <div class="form-group">
                            <label for="channel_id">Select A Channel:</label>
                            <select name="channel_id" id="channel_id" class="form-control" required>
                                <option value="">Choose one.....</option>
                                @foreach($channels as $channel)
                                 <option value="{{$channel->id}}" {{old('channel_id') == $channel->id ? 'selected' : ''}}>
                                    {{$channel->name}}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="title">Title:</label>
                            <input type="title" name="title" class="form-control" id="title" placeholder="Title" value="{{old('title')}}" required>
                        </div>
                        <div class="form-group">
                            <p>Upload a image/video</p>   
                            <input type="file" name="image" accept="image/*" class="@error('image') is-invalid @enderror">
                            @error('image')
                            <div class="alert alert-danger">{{ $message }}</div>
                            @enderror
                            @if (session('error-image'))
                            <div class="alert alert-danger">
                              {{ session('error-image') }}
                            </div>
                            @endif
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">Publish</button>
                        </div>
                    </form>
                </div>

.....

Though of sharing the same form for image & video but that does not sound good way of doing it. How does multi part uploading will look like in my case?

Activity icon

Replied to How To Upload Video?

So should I separate the controller logic for handling video upload?

Activity icon

Started a new Conversation How To Upload Video?

I want to allow user to choose to update a normal post, an image or video. So far, I can upload post and image and they both hit the same controller.

thread controller:

  public function store(Request $request){
          //create thread for post
            if($request->has('post')){
                //validate the request
                $this->validate($request,[
                    'title' => 'required',
                    'body' => 'required',
                    'channel_id' => 'required|exists:channels,id'
                ]);

                //Create a new instance of thread  
                $thread = Thread::create([
                    'user_id' => auth()->id(),
                    'channel_id' => request('channel_id'),
                    'title' => request('title'),
                    'body' => request('body')
                    ]);
                    
                // Success new thread created
                Session::flash('message', 'Thread has been published');
                return redirect($thread->path());

        }
        

        //create thread for image/video
        if($request->has('image')){
            //check if request has image
            if($request->hasFile('image')){
              //check if image is valid uploaded
              if($request->file('image')->isValid()){

                $validated = $request->validate([  
                    'title' => 'required',
                    'channel_id' => 'required|exists:channels,id',    
                    'image' => 'required|mimes:jpeg,png,jpg|max:1014',
                ]);

                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                Image::make($image)->resize(500,500)->save(public_path('/images/uploads/threads/images/'. $filename));       
           
                //create new post 
                $thread = Thread::create([
                    'user_id' => auth()->id(),
                    'channel_id' => request('channel_id'),
                    'title' => request('title'),
                    'image' => $filename
                     ]);

                 // Success new thread created
                Session::flash('message', 'Thread has been published');
                return redirect($thread->path());
             }        
          return back()->with('error-image','Image is not valid');
         }
        
      }
      return back()->with('error-image','Please upload an image');
            
    }

However, how do I go about the validation rules to validate what video files and size it can fit?

Or should I create a separate controller just for uploading video?

What's the best way to handle this?

Apr
06
1 week ago
Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

Okay. What if I change my migration for user info instead of the relationship model like :

$table -> string(‘avatar’”)->default(default.jpeg)

Is this the same as your solution ?

Apr
05
1 week ago
Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

Yes I didn't mention.

I have this relationship in my User model

public function userInfo()
{
    return $this->hasOne(UserInfo::class);
}

Will his solution be better?

Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

You mean change:

public function userInfo()
{
    return $this->hasOne(UserInfo::class)->withDefault([
        'avatar' => 'default.jpeg'
    ]);
}

to

public function info()
{
    return $this->hasOne(UserInfo::class)->withDefault([
        'avatar' => 'default.jpeg'
    ]);
}

?

Or do you mean to add these two as well?

Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

@tykus Just wondering why my original way will not evaluate the else statement?

Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

Thanks, didn't know I can resolve this using null coalescing operator.

Activity icon

Replied to Laravel - Display Avatar If User Upload It Or Use Default Image

Based on the doc, it means it will return the default pic if the "less hand side" is null or otherwise?

Activity icon

Started a new Conversation Laravel - Display Avatar If User Upload It Or Use Default Image

I am allowing user to upload an avatar (profile image) in their profile. While uploading avatar is entirely optional, if user does not have avatar, a default image will be used. However, checking whether a user has an avatar uploaded or not in my

show.blade.php:

 @if($user->userInfo->avatar)
                        <img src="{{asset('/images/uploads/avatars/'. $user->userInfo->avatar)}}"  class="img-circle" height="120" width="120" alt="avatar">      
                        @else
                        <img src="{{asset('/images/uploads/avatars/default.jpeg')}}"  class="img-circle" height="120" width="120" alt="avatar">      
                        @endif

It throws the error:

Trying to get property 'avatar' of non-object

I understand my user info is null but why would it throw the error since if it's null then it shall execute the else statement and display the default image..?

Apr
01
2 weeks ago
Activity icon

Replied to How To Upload Array Of Files In Vue.js And Laravel ?

Your issue is most like at the handleSubmit() method when you try to use data.append(......).

In your controller, die and dump the values to see if you're getting the intended data.

Activity icon

Replied to Validation Error Return To Second Tab

Okay I tested, it doesn't accept array so I have to manually write it multiple times.

Activity icon

Replied to Validation Error Return To Second Tab

I see. However, can the has method accept more than one?

Because I have three fields that need to be validated, i.e

 <form class="form-horizontal" method="POST" action="{{route('changePassword')}}">
                       @csrf
                        <div class="form-group{{ $errors->has('current-password') ? ' has-error' : '' }}">
                            <label for="new-password" class="col-md-4 control-label">Current Password</label>
                            <div class="col-md-6">
                                <input id="current-password" type="password" class="form-control" name="current-password" required>
                                @if ($errors->has('current-password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('current-password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('new-password') ? ' has-error' : '' }}">
                            <label for="new-password" class="col-md-4 control-label">New Password</label>

                            <div class="col-md-6">
                                <input id="new-password" type="password" class="form-control" name="new-password" required>

                                @if ($errors->has('new-password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('new-password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="new-password-confirm" class="col-md-4 control-label">Confirm New Password</label>

                            <div class="col-md-6">
                                <input id="new-password-confirm" type="password" class="form-control" name="new-password_confirmation" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Change Password
                                </button>
                            </div>
                        </div>
                    </form>

Do I have to write it out three separate times?

Activity icon

Replied to Validation Error Return To Second Tab

can you give an example of how it looks like?

Activity icon

Replied to Validation Error Return To Second Tab

Thanks, can you explain how would this work?

Activity icon

Started a new Conversation Validation Error Return To Second Tab

I have a tab panel using bootstrap and the primary tab(1st tab) shows my profile information and the second tab allows me to edit the details of my profile. Upon navigating to the second tab, if I submit the form without any input to fail the validation, it will redirect back to the first primary tab. Then I have to select the second tab again to see the validation error.

Is there any way I return to the second tab immediately?

I assume there's required some javascript handling but any other suggestion.

blade:

  <div class="row my-2">
      <div class="col-lg-8 order-lg-2">
          <ul class="nav nav-tabs">
              <li class="nav-item">
                  <a href="" data-target="#profile" data-toggle="tab" class="nav-link active">Profile</a>
              </li>
              @can('update',$user)
              <li class="nav-item">
                  <a href="" data-target="#edit" data-toggle="tab" class="nav-link">Edit</a>
              </li>
              @endcan
          </ul>
          <div class="tab-content py-4">
              <div class="tab-pane active" id="profile">
                  <h5 class="mb-3">User Profile</h5>
                  <div class="row">
                      <div class="col-md-6">
                          <h6>Name</h6>
                          <p>
                             {{$user->name}}
                          </p>
                          <h6>Email</h6>
                          <p>
                             {{$user->email}}
                          </p>
                      </div>
                  </div>
                  <!--/row-->
              </div>
              <div class="tab-pane" id="edit">
                  <form method="POST" action="{{route('profile.update',[$user])}}">
                      @csrf
                      @method('PATCH')
                      <div class="form-group row">
                          <label class="col-lg-3 col-form-label form-control-label">Name</label>
                          <div class="col-lg-9">
                              <input class="form-control" type="text" id="name" name="name" onkeyup="checkInput()" value="{{$user->name}}" required>
                          </div>
                      </div>
                      <div class="form-group row">
                          <label class="col-lg-3 col-form-label form-control-label">Email</label>
                          <div class="col-lg-9">
                              <input class="form-control" type="email" name="email" value="{{$user->email}}" disabled>
                          </div>
                      </div>                  
                      <div class="form-group row">
                          <label class="col-lg-3 col-form-label form-control-label"></label>
                          <div class="col-lg-9">
                              <input type="reset" class="btn btn-secondary" value="Cancel">
                              <button type="submit" id="save-btn" class="btn btn-primary" disabled>Save Changes</button>
                          </div>
                      </div>
                      @if(count($errors))
                      <ul class="alert alert-danger">
                          @foreach($errors->all() as $error)
                              <li>{{$error}}</li>
                          @endforeach
                      </ul>
                      @endif
                  </form>
              </div>
          </div>
      </div>
  </div>
</div>

controller:

public function update(UpdateProfileRequest $request, User $user){

        $this->authorize('update',$user);

        $validated = $request->validated();

        $user->update([
            'name' => $request->input('name')
        ]);


        return redirect($user->path())->with('message',"Profile has been updated");;
    }
Mar
31
2 weeks ago
Activity icon

Replied to Best Way To Filter Posts

Not really a search filter. Just have an anchor tag like popular post and clicking on it returns data with popular posts. Similar with filter by user, it becomes “My post” and return all the post by the user.

Activity icon

Replied to Best Way To Filter Posts

what about other filtering like by username?

Activity icon

Started a new Conversation Best Way To Filter Posts

I want to display all the posts in a page and using the index() method to return all the posts. Now, assuming I also want to filter the posts by username or with the most replies count, I'll add methods filterByUsername() and filterByPopular().

Is there other way to accomplish this rather than create methods as the filter will eventually piled up?

Mar
29
2 weeks ago
Activity icon

Replied to Css - Display Inline Block And Align Content To Right?

It didn't work though because the other user message will overlap in same row as my message.

     <div class="card-body scroll">
                     <div v-for="message in messages" :key="message.id">
                        <my-message
                        v-if="message.user == userId"
                        :message="message.text"
                        ></my-message>

                        <message
                        v-if="message.user != userId"
                        :message="message.text"
                        :user="message.user"
                        ></message>
                    </div>
                </div>

Are there other alternatives?

Activity icon

Started a new Conversation Css - Display Inline Block And Align Content To Right?

I made a chat box where I can user can send messages. Any messages sent from my end is on the right side of the chat box while other messages from other users will end on the left side.

So, this is how I style it for my messages:

<template>
        <div class="alert alert-success notification" role="alert">
            {{message}}
        </div>
</template>

<script>
    export default {
        props: [
            'message'
        ]
    }
</script>

<style scoped>
    .notification {
        text-align: right;
        margin-bottom: 1em;
        display: inline-block;
    }
</style>

Using text-align to right will work but I had to fit the text within the content so I added inline-block but the text does not align to the right and aligns to the left. I tried using float:right but while it does works but it overlaps with the subsequent messages that I sent that ends up on the same row.

What property should I use to fix this?

Mar
28
2 weeks ago
Activity icon

Replied to Websocket Not Showing Real Time Statistics

May I know why is the host set to transport-web-app.test?

Mar
27
3 weeks ago
Activity icon

Started a new Conversation Websocket Not Showing Real Time Statistics

Gonna take a shot in a dark here for anyone using the package beyondcode/websockets. I can't seem to get my real time statistics to show anything in my websocket dashboard provided by the package.

These are my configuration:

broadcasting.php:

   'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http',
            ],
        ],
....

websocket.php:

 'apps' => [
        [
            'id' => env('PUSHER_APP_ID'),
            'name' => env('APP_NAME'),
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'path' => env('PUSHER_APP_PATH'),
            'capacity' => null,
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
    ],

My .env has the correct url:

APP_URL=http://forum.test

I am hosting mine locally using Valet so everytime I tried restarting the websocket server. the real time stats is just empty. How do I resolve this?

Mar
22
3 weeks ago
Activity icon

Replied to Suggestion On How To Build Real Time Chat?

Thanks for the link. yea many of the commenters above suggested to use web sockets as well as an alternative to pusher (although I think websockets uses pusher as well).

Activity icon

Replied to Suggestion On How To Build Real Time Chat?

Thanks, so the messenger that you're working is open source right?

Would you recommend it as stable for the current version it's released?

I tried using the munifo/chatify package but it requires me to downgrade my PHP version.

https://www.youtube.com/watch?v=gjo74FUJJPI

Mar
20
4 weeks ago
Activity icon

Started a new Conversation Suggestion On How To Build Real Time Chat?

I want to add a real time messaging chat system to my forum and had a research and looked about package called chatify, while it looks really cool but there's still many issues with it.

I figured I need to use Pusher (it's not free per say) but I would like to know what is the best way to do it using laravel ?

Suggest me some good packages or your expert views on them.

Activity icon

Started a new Conversation Chatify Installation?

Was wondering anyone that uses chatify comes across the version incompatible issue :

    - pusher/pusher-php-server v3.4.0 requires php >=5.4 <7.3 -> your php version (7.4.8) does not satisfy that requirement.
    - pusher/pusher-php-server v3.4.1 requires php >=5.4 <7.4 -> your php version (7.4.8) does not satisfy that requirement.
    - Root composer.json requires pusher/pusher-php-server ~3.4 -> satisfiable by pusher/pusher-php-server[v3.4.0, v3.4.1].

As far as I know, the current chatify version (v1) only supports pusher v3.4. I installed to that version but from the message above, it seems like I have to downgrade my php version, I do not know if it's recommended.

In my composer.json file, my php version is listed as 7.2.5 but not 7.4.8 so I do not understand how come it does not show the correct version as shown in my json file?

Activity icon

Replied to Chatify Not Installing

Did you manage to solve it?

Mar
18
4 weeks ago
Activity icon

Replied to Passing Data Via Ajax Using Object Vs Json?

So the $request is able to receive the input regardless of the "body" or body?

Activity icon

Started a new Conversation Passing Data Via Ajax Using Object Vs Json?

I was wondering which way is more efficient if I want to use jquery ajax to send a request.

For example, passing data as object:

   $.ajax({
                url:"{{route('reply.update',$reply->id)}}",
                method:'PUT',
                data: {
                    body: $('#body-{{$reply->id}}').val()
                },
                success:function(response){
                    console.log(response);
                },
                error:function(error){
                    console.log(error);
                   
                }
            });
        });

Passing as JSON:

   $.ajax({
                url:"{{route('reply.update',$reply->id)}}",
                method:'PUT',
				dataType: 'JSON'
                data: {
                    "body": "$('#body-{{$reply->id}}').val()"
                },
                success:function(response){
                    console.log(response);
                },
                error:function(error){
                    console.log(error);
                  
                }
            });
        });

And in the controller, can I just access both method using $request->body or $request->input('body') ?

As I want to clear up confusion, which way should I use?

Mar
17
1 month ago
Activity icon

Started a new Conversation API How To Get Records Belong To User

I have an admin user who can create all the listings and am using API with postman to retrieve listings that belongs to a user.

My ListingController:

  public function getListing(Request $request){

        $listings = Listing::where('user_id',$request->input('user_id'))->get();

        if($listings->isEmpty()){
            return response(['error' => 'No records found']);
        }

        return response([
            'status' => 200,
            'message' => 'success',
            'result' => [
                'data' => $listings,          
            ],
            ]);
    }

api.php:

//Route for get listing
Route::middleware(['auth:api'])->group(function () {
    Route::get('/listing/get','API\[email protected]');
});

While in postman, I added an authorize token from passport and added a user_id in the body - form-data - key section and hit send but it always return with no records found

The issue I am guessing if it could not receive the user id input but how come it does not work?

Activity icon

Replied to Add New Column Into Api Response?

I thought you could call a foreach to the collection and print them individually.

Activity icon

Replied to Add New Column Into Api Response?

then how do I loop individual data from the response?

Say I don't want certain columns to be shown from Listing::all()

Activity icon

Replied to Add New Column Into Api Response?

Is there a way to avoid using db query and use eloquent instead?

Activity icon

Replied to Add New Column Into Api Response?

What does it do?

Honestly, I was given this question and I think it doesn't make much sense since you are required two points to calculate the distance and I was only given one.

Activity icon

Replied to Add New Column Into Api Response?

I don't have a distance column in my database. I believed the distance is calculated by dividing the latitude/longitude,assuming that is the case.

Activity icon

Started a new Conversation Add New Column Into Api Response?

I am using laravel passport and postman to access all the records of listings that belong to a user.

So in my controller:

 public function getListing(){
        $listings = Listing::all();
        return response([
            'status' => 200,
            'message' => 'success',
            'result' => [
                'data' => $listings,          
            ],
            ]);
    }

and it will return result like below:

{
    "status": 200,
    "message": "success",
    "result": {
        "data": [
            {
                "id": 2,
                "name": "OUG",
                "latitude": 60,
                "longitude": 80,
                "user_id": 1,
                "created_at": "2021-03-17T11:28:03.000000Z",
                "updated_at": "2021-03-17T13:09:38.000000Z"
            },
            {
                "id": 4,
                "name": "new listing",
                "latitude": 80.5,
                "longitude": 80.5,
                "user_id": 1,
                "created_at": "2021-03-17T12:05:41.000000Z",
                "updated_at": "2021-03-17T12:05:41.000000Z"
            },
            {
                "id": 5,
                "name": "New listing 2",
                "latitude": -90,
                "longitude": -180,
                "user_id": 1,
                "created_at": "2021-03-17T13:10:50.000000Z",
                "updated_at": "2021-03-17T13:10:50.000000Z"
            }
        ]
    }
}

I would like to display it like below:

{
  "status":200,
  "message":"Success",
  "result":{
   "current_page":1,
   "data":[
     {
      "id":4,
      "name":"Starbucks Mid Valley",
      "distance":"0.6",
      "created_at":"2021-03-10 12:24:38",
      "updated_at":"2021-03-10 12:24:38"
     },
     {
      "id":9,
      "name":"Burger King",
      "distance":"0.8",
      "created_at":"2021-03-10 12:24:38",
      "updated_at":"2021-03-10 12:24:38"
     },......

How do I calculate the distance to display it?

Activity icon

Started a new Conversation ParseError: Syntax Error, Unexpected 'Parser' (T_STRING), Expecting Function (T_FUNCTION) Or Const (T_CONST)

I am building an api for login an user and using postman to test it out.

When I send the request, it says:

ParseError: syntax error, unexpected 'Parser' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

I think it might be an incompatible version for laravel passport with php version. This is my current configuration in composer.json:

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2.5",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^1.0",
        "guzzlehttp/guzzle": "^6.3",
        "laravel/framework": "^7.0",
        "laravel/passport": "~9.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^2.4"
    },

I have no idea what do I need to do to fix it.

Activity icon

Replied to Validate Latitude

 /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:255',
            'latitude' => 'required|between:-90,90',
            'longitude' => 'required|between:-180,180'
        ];
    }

    /**
    * Get the error messages for the defined validation rules.
    *
    * @return array
    */
    public function messages()
    {
        return [
            'name.max' => 'The name has exceeded the limit',
            'latitude.between' => 'The latitude must be in range between -90 and 90',
            'longitude.between' => 'The longitude mus be in range between -180 and 180'
        ];
    }
Activity icon

Replied to Validate Latitude

It says data truncated for latitude.....

Activity icon

Started a new Conversation Validate Latitude

I created a form request to validate a latitude input. The value can be from -90 and 90 and has to be numeric only and can be double as well.

My validation is like this:

'required|between:-90,90'

Do I need to use regular expression ?

Activity icon

Replied to Change Redirect To After Login

why can't I use view?

Activity icon

Started a new Conversation Change Redirect To After Login

I wanted to modify the LoginController and I removed the redirect to and put this in:

   /**
     * Where to redirect users after login.
     *
     *
     */
   
    public function redirectedPath(){
        if(auth()->user()->role_type){
            return view('admin.dashboard');
        }else{
            dd(auth()->user());
            return view('home');
        }
    }

When I commented it out, it still always redirect to home page. How do I make this logic work?

Mar
16
1 month ago
Activity icon

Replied to Using Same Controller For Web Route And Api Route?

So for API, model should be stay as a single entity but for controllers, it should have a separate layer for API alone, correct(since API don't return views)?

What do you mean by duplicated code?