FareedR

FareedR

Member Since 1 Year Ago

Experience Points 5,620
Experience Level 2

4,380 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 14
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

04 Sep
1 week ago

FareedR left a reply on Date In Carbon

@bobbybouwmann @resin @richard for more specific on my use case

if in database are empty, the system will display on selection dropdown from January 2019 until December 2023 ( if i want 4 years onwards)

if in database already have August 2019 , in selection dropdown, will not display it. 

sorry if my question confusing you guys.

FareedR started a new conversation Date In Carbon

how can i make a query where current month and year onwards for the next 4 years . previous month and year will not display. example given ;

//database
id| month | 
1   2019-08-1 

//example
September 2019 - onwards
20 Aug
3 weeks ago

FareedR started a new conversation Passport Authentication

Can someone show me best practices for logout using Passport ? currently using this method for my API . should i put \Auth::logout() and \Session::flush() ? or passport already done it ?

$request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out',
            'status' => true
        ],200);
06 Aug
1 month ago

FareedR left a reply on Eloquent Design

@michapietsch thank you for your help sir. i learn something new about this

02 Aug
1 month ago

FareedR left a reply on Eloquent Design

@michapietsch i get an error for that query .

// error
Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'user_categories' (SQL: select `user_categories`.*, `user_categories`.`user_id` as `pivot_user_id`, `user_categories`.`category_id` as `pivot_category_id` from `user_categories` inner join `user_categories` on `user_categories`.`id` = `user_categories`.`category_id` where `user_categories`.`user_id`

FareedR left a reply on Eloquent Design

@snapey @michapietsch thankyou for your time . how can i simplify my queries on this method. it took 3 queries to achieve that . do you have any idea to simplify it ? thanks in advance

// User.php
public function categories()
    {
        return $this->belongsToMany(UserCategory::class,'user_categories','user_id','category_id');
    }
    
// UserCategory.php
public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id');
    }
// Category.php
 public function userCategory()
    {
        return $this->hasMany(UserCategory::class);
    }

// Controller
public function dashboard()
    {
        $userID = \Auth::user()->id;
        $categories = UserCategory::where('user_id',$userID)->get();
        foreach($categories as $category){
            $collectionCategoryID [] = $category->category_id;
        }
        $posts = Post::whereIn('category_id',$collectionCategoryID)->get();
    }
01 Aug
1 month ago

FareedR left a reply on Eloquent Design

@aurawindsurfing

can i know how to implement whereUser() and whereCategory in Post.php ? example below .

public function whereUser()
{
    return $this->hasOne(UserCategory::class,'user_id');
}
31 Jul
1 month ago

FareedR started a new conversation Eloquent Design

how can i retrieve all posts for user_id 1 based on its interests on that category ? Should i use whereHas or something else?

// database

// categories
id | title
1   technology

//user_has_categories
user_id | category_id
1           1

//posts
id | user_id | category_id | title
1   3           1       content
26 Jul
1 month ago

FareedR left a reply on Redirect User Using API For Mobile App

is there any source that i can refer on authentication process using API ?

FareedR started a new conversation Redirect User Using API For Mobile App

How can i redirect successful login user to their dashboard ? should i setting it from mobile app ? or i need to change return response to return redirect()->route('dashboard') ? sorry . first time in API with mobile app .

//controller
public function login(Request $request)
    {
        $request->validate([
            'email' => "required",
            'password' => "required"
        ]);

        $credentials = request(['email','password']);

        // Check credentials
        if(!Auth::attempt($credentials)){
            return response()->json([
                'message' => 'Incorrect password or email. Please try again'
            ],401);
        }elseif(!Auth::user()->email_verified){
            return response()->json([
                'message' => 'Please verify your e-mail address'
            ],401);
        }
        else{
            $user = $request->user();

            // Create user token
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->save();
            
            return response()->json([
                'message' => 'Successfully Login',
                'token' => $tokenResult
            ],201);
            
        }
02 Jun
3 months ago

FareedR left a reply on Contact Us Form

i solved it and it works . I think subject() is deprecated . when i remove it, everything is ok .

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $message,$subject;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($from,$subject,$message)
    {
        $this->from($from);
        $this->subject = $subject;
        $this->message = $message;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.guest.contact')
                    ->with([
                        'subjects' => $this->subject,
                        'messages' => $this->message,
                    ]);
    }
}

FareedR left a reply on Contact Us Form

in my use case , system admin should receive an email from guest in Contact Us page .

FareedR left a reply on Contact Us Form

value for $from is "sender" . and the recipient is system admin .

FareedR left a reply on Contact Us Form

@JOHNBRAUN - this is my view code

<p>
Message: {{ $message }}
</p>

FareedR left a reply on Contact Us Form

@JOHNBRAUN - its happen on this code because i try dd before & after return process . first dd come out but 2nd dd throw the error that i gave just now.

dd('example1');
return $this->subject($subject)
                    ->from($from)
                    ->to('[email protected]')
                    ->view('emails.guest.contact')
                    ->with([
                        'message' => $this->message
                    ]);
dd('example2');

FareedR left a reply on Contact Us Form

@JOHNBRAUN - sorry for the late reply . error that i get stated below

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
[] operator not supported for strings
01 Jun
3 months ago

FareedR started a new conversation Contact Us Form

why i keep receive this error ? i'm using php artisan make:mail & i'm using mailtrap for testing email. do i need a real domain to test the email?

//error
protected function setAddress($address, $name = null, $property = 'to')
    {
        foreach ($this->addressesToArray($address, $name) as $recipient) {
            $recipient = $this->normalizeRecipient($recipient);
 
            $this->{$property}[] = [
                'name' => $recipient->name ?? null,
                'address' => $recipient->email,
            ];
        }
 
        return $this;
    }

this is my code

// controller
    public function sendEmail(SendEmailFormRequest $request)
    {
        $from = $request->get('email');
        $subject = $request->get('subject');
        $message = $request->get('message');
    // will pass to SendEmail.php
        Mail::send(new SendEmail($from,$subject,$message));
    }
// sendemail.php
class SendEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $email;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($from,$subject,$message)
    {
        $this->from = $from;
        $this->subject = $subject;
        $this->message = $message;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $from = $this->from;
        $subject = $this->subject;
        
        return $this->subject($subject)
                    ->from($from)
                    ->to('[email protected]')
                    ->view('emails.guest.contact')
                    ->with([
                        'message' => $this->message
                    ]);
    }
}
16 May
3 months ago

FareedR started a new conversation Update Data With Current Image File Using Same Form Request From Store Function

how can i use same form request on update function ? it keep display to me " Image field is required " but i dont want to update image , i just want to update other data only . not image .

// form request
public function rules()
    {
        return [
            'title' => 'required|min:6',
            'image' => 'required|image|mimes:png|dimensions:width=1920,height=1076',
            'description' => 'required|min:6',
            'status' => 'required'
        ];
    }
//controller
 public function updateBanner(BannerFormRequest $request,$id)
    {
        $banner = Banner::findOrFail($id);

        if($request->hasFile('image')){
            $oldImage = Storage::disk('public')->delete('{{ $banner->image }}');
            $image = $request->file('image')->store('banners','public');
        }

        $banner->title = $request->get('title');
        $banner->description = $request->get('description');
        $banner->status = $request->get('status');
        $banner->save();

        toastr()->success('Banner has been updated');
        return redirect()->route('list-banner');
    }
//blade
<div class="block-content">
            <form action="{{ route('update-banner', $banner->id) }}" method="post" enctype="multipart/data">
            @csrf
            @method('PATCH')
                <div class="form-group">
                    <label for="input-title">Title</label>
                    <input type="text" class="form-control" name="title" value="{{ $banner->title }}">
                </div>
                <div class="form-group">
                    <label for="input-image">Image</label>
                    <input type="file" class="form-control" name="image">
                    <div class="img">
                        <img class="img-fluid" style="width:50%" src="{{ Storage::url($banner->image) }}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="input-description">Description</label>
                    <input type="text" class="form-control" name="description" value="{{ $banner->description }}">
                </div>
                <div class="form-group">
                    <label for="input-status">Status</label>
                    <select name="status" class="form-control">
                        @if($banner->status)
                        <option value="0">Inactive</option>
                        <option value="1" selected>Active</option>
                        @else
                        <option value="0" selected>Inactive</option>
                        <option value="1">Active</option>
                        @endif
                    </select>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-alt-primary">Submit</button>
                </div>
            </form>
        </div>
04 May
4 months ago

FareedR left a reply on What Should I Response In Login Process ?

@TISUCHI - currently i'm using it .

FareedR left a reply on What Should I Response In Login Process ?

@tisuchi @roborobok i think i let my API like this . make sense ?

//api routes
Route::post('/login','API\V1\Auth\[email protected]')->name('login');

Route::prefix('student')->middleware(['auth:api','role:student'])->group(function(){
    Route::get('/','API\V1\Student\[email protected]')->name('view-home-student');
});

//auth controller
public function login(Request $request)
    {
        $request->validate([
            'id_no' => 'required|string',
            'password' => 'required|string'
        ]);

        $credentials = request(['id_no','password']);

        // Check credentials
        if(!Auth::attempt($credentials)){
            return response()->json([
                'message' => 'Unauthorized'
            ],401);
        }else{
            $user = $request->user();

            // Create user token
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->save();
            
            return response()->json([
                'message' => 'Successfully Login'
            ],201);
            
        }
    }

//student controller
public function home(Request $request)
    {
        $user = $request->user()

        return response()->json([
            // User
            'student_id' => $user->id_no,
            // Campus
            'campus_name' => $user->campus->name,
            // Profile
            'student_name' => $user->students()->first()->name,
            'student_id' => $user->students()->first()->id,
            'avatar' => $user->students()->first()->profile->avatar,
        ],201);
    }

FareedR left a reply on What Should I Response In Login Process ?

which one do i need to do ? what i understanding is , endpoint is giving the data to the view . but in my case . i just need to check if user valid and has student role , then user can see all the club in mobile app.

controller 
    if($user->hasRole('student')){
                $club = Club::all();
                return response()->json([
                    'access_token' => $tokenResult->accessToken,
                    'token_type' => 'Bearer',
                    'user' => $user,
                    'club' => $club
                ],201);
            }

or

api.php
Route::prefix('student')->middleware(['auth:api','role:student'])->group(function(){
    Route::get('view-home-student','API\V1\Student\[email protected]')->name('view-home-student');
});

controller
//auth controller
    if($user->hasRole('student')){
                return redirect('/student');
            }

//student controller
public function home(Request $request)
    {
        $user = $request->user();
        $club = Club::all();
        return response()->json([
            'user' => $user,
            'club' => $club
        ],201);
    }

FareedR left a reply on What Should I Response In Login Process ?

@ROBOROBOK - yup it's SPA . basically, at this point , i just want to check if user valid and has student role, then user have the right to view as student and list of club . do i need to make one more endpoint just to retrieve user info and club info ?

FareedR started a new conversation What Should I Response In Login Process ?

I'm doing API right now . what should i response if user exist and has that role because if in web, we just redirect it to folder . how about in API ? should do the same thing or just return response success ? p/s first time developing an API

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'id_no' => 'required|string',
            'password' => 'required|string'
        ]);

        $credentials = request(['id_no','password']);

        // Check credentials
        if(!Auth::attempt($credentials)){
            return response()->json([
                'message' => 'Unauthorized'
            ],401);
        }else{
            $user = $request->user();

            // Create user token
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->save();
            
            if($user->hasRole('student')){
                return response()->json([
                    'access_token' => $tokenResult->accessToken,
                    'token_type' => 'Bearer',
                    'user' => $user
                ],201);
            }
        }
    }
}
03 May
4 months ago

FareedR left a reply on Pass Current Id And Date From Table Submit Button

// blade
<td> 
    <form action = "{{ route('anything', $user->id) }}">
    @csrf
        <input type="date" name="startdate">
        <button type="submit">Submit</submit>
    </form>
</td>

// controller
public function anything(Request $request,$id)
{
    $request->get('start_date');
}

FareedR started a new conversation Play Around With API + Passport

Currently digging deeper in API and i play around with simple auth process . My question is do i need to make function logout for each role ( in future ) for example , i have 3 role . so do i need to implement the same function logout into each role ? Based on my understanding, API are playing with token right ? so it doesnt same like web which is we can call " auth()->user()->id " .

Route::post('/login','API\V1\Auth\[email protected]')->name('login');
Route::post('/register','API\V1\Auth\[email protected]')->name('register');

Route::prefix('user')->middleware('auth:api')->group(function(){
    Route::get('/logout','API\V1\Auth\[email protected]')->name('logout');
    Route::get('user-profile/{id}','API\V1\User\[email protected]')->name('view-user-profile');
    Route::post('update-user-profile/{id}','API\V1\User\[email protected]')->name('update-user-profile');
});
30 Apr
4 months ago

FareedR left a reply on How Can I Get {id} From Url ?

its done and thank you for helping me !

// compact the id in controller and pass it to view as below 
<form action="{{ route('store-venue-superadmin', $id ) }}" method="post">

// return view after store with following code 
return redirect()->route('view-list-venue-superadmin',['id' => $id]);

FareedR left a reply on How Can I Get {id} From Url ?

@JLRDW - how can I keep {5} to other view ?

FareedR started a new conversation How Can I Get {id} From Url ?

web.php
 Route::get('/list-venue/{id}','Superadmin\[email protected]');
 Route::get('/create-venue/{id}','Superadmin\[email protected]');

controller
public function listVenue($id)
    {
        $venues = Venue::where('campus_id',$id)->get();

        return view('superadmin.venues.index',compact('venues'));
    }

// retrieve id from function above . 

 public function storeVenueForm( Request $request,$id)
    {
        $venue = new Venue ([
            'campus_id' => $id,
            'name' => $request->get('name'),
            'status' => $request->get('status')
        ]);

        $venue->save();

29 Apr
4 months ago

FareedR left a reply on Getting Data Using With() Relation In Controller To Js

@TALINON - thankyou ! it works for me . new knowledge for me regarding to '->' things . thanks again !

FareedR left a reply on Getting Data Using With() Relation In Controller To Js

@TOMI - yup . i've done it . i got a relation "campuses" full with data . but when put it as "campusObj.campuses->id" . it didnt display anything .

https://imgur.com/QSKqxRx

FareedR started a new conversation Getting Data Using With() Relation In Controller To Js

How can i get campus data ?

// db
universities
id | subdomain |

campus
id | university_id | name |

// script
<script>
            $('#btnSearch').on('click',function (event){
        // getting subdomain here
                var university = $('#university').val()
                $.ajax({
                    type: "GET",
                    url: "{{ url('/get-university') }}" + '/' + university,
                    data: {university : university},
                    success: function(data){
                        $('#availableCampus').empty()
                        $.each(data,function(index, campusObj){
                            $('#availableCampus').append('<option value="{{'+campusObj.id+'}}">'+campusObj.name+ '</option>')
                        });
                    },
                    error: function(){
                        swal({
                            title: "Opps",
                            text: "University doesnt exist",
                            icon: "error",
                            timer: 1500
                        })
                    }
                })
            });
        </script>

//controller
public function getUniversity($university)
    {
        $availableCampus = University::with('campuses')->where('subdomain','=',$university)->get();
        return \Response::json($availableCampus);
    }
27 Apr
4 months ago

FareedR left a reply on Send File On Modal Using AJAX

@FTIERSCH - oh ya ! it's my mistake . thankyou !

FareedR left a reply on Send File On Modal Using AJAX

@CRONIX - i've tried his tutorial . file transfer is working but i didnt get event_id from "var event" when i click the button submit .i've tried input type "submit & button type button . the result is same . url that i get is "/club/upload-document-event-club/object Object" btw in controller the param is public function whatever(Request $request,$id). i think it doesnt matter right ?

view
<button type="button" class="btn btn-sm btn-rounded btn-warning" data-toggle="modal" data-target="#modal-normal" data-event="{{ $event->id }}" title="Upload Document">
    Upload Approval Document
</button>


<div class="modal" id="modal-normal" tabindex="-1" role="dialog" aria-labelledby="modal-normal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="form" method="post" enctype="multipart/form-data">
            @csrf
                <div class="block block-themed block-transparent mb-0">
                    <div class="block-header bg-primary-dark">
                        <h3 class="block-title">Upload Approval Document</h3>
                        <div class="block-options">
                            <button type="button" class="btn-block-option" data-dismiss="modal" aria-label="Close">
                                <i class="si si-close"></i>
                            </button>
                        </div>
                    </div>
                    <div class="block-content">
                        <input type="file" class="form-control" id="file" name="supported_document">
                        <span class="text-danger"> PDF FILE ONLY </span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-alt-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-alt-secondary" id="uploadApprovalDocument">Submit</button>
                    <!-- <input type="submit" class="btn btn-alt-success" id="uploadApprovalDocument" value="Submit">  -->
                </div>
            </form>
        </div>
    </div>
</div>

script
$('#modal-normal').on('show.bs.modal', function(e){
        var button = $(e.relatedTarget)
        var event = button.data('event')
        var modal = $(this)
    
    // i still get the ID from button . 
        console.log('before',event);

        // button to click for submit form inside modal
        $('#uploadApprovalDocument').on('click', function(event){
            // i lost the ID when i click that button
        console.log('after',event);
            // stop submit form natively. 
            event.preventDefault();
            var form = $('#form')[0];
            var data = new FormData(form);
            swal({
                title:"Are you sure this is correct file to submit?",
                text:"Once submit, you can't change the file",
                icon: "warning",
                dangerMode: true,
            })
            .then((willUpload) => {
                if (willUpload) {
                        // if TRUE, send input file to controller based on eventID
                        $.ajax({
                        type: "POST",
                        enctype: "multipart/form-data",
                        url: "{{ url('/club/upload-document-event-club') }}" + '/' + event,
                        data: data,
                        processData: false,
                        contentType: false,
                        cache: false,
                        success: function(){
                            console.log('posted',event);
                            console.log(data);
                            swal({
                            title: "Approval Document has been sent!",
                            text: "Click OK to refresh the page",
                            icon: "success",
                            }).then(function(){
                                location.reload();
                            });
                        },
                        error : function(e){
                            console.log(e);
                            swal({
                                title: "Opps...",
                                text : "Something wrong occured",
                                icon: "error",
                                timer: 1500
                            })
                            }
                        })
                }else{
                    swal("Nothing happens here");
                }
            });
        })
    });
26 Apr
4 months ago

FareedR left a reply on Send File On Modal Using AJAX

@FTIERSCH - i really lost right now . i can't think anything . thankyou for you reply btw .

FareedR started a new conversation Send File On Modal Using AJAX

i guess i'm missing something in ajax posting, but i couldn't figure it out

 <button type="button" class="btn btn-sm btn-rounded btn-warning" data-toggle="modal" data-target="#modal-normal" data-event="{{ $event->id }}" title="Upload Document">
    Upload Approval Document
</button>

// Modal that trigger button above
<div class="modal" id="modal-normal" tabindex="-1" role="dialog" aria-labelledby="modal-normal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="block block-themed block-transparent mb-0">
                <div class="block-header bg-primary-dark">
                    <h3 class="block-title">Upload Approval Document</h3>
                    <div class="block-options">
                        <button type="button" class="btn-block-option" data-dismiss="modal" aria-label="Close">
                            <i class="si si-close"></i>
                        </button>
                    </div>
                </div>
                <div class="block-content">
                    <form id="form" method="post" enctype="multipart/form-data">
                    @csrf
                        <input type="file" class="form-control" id="file" name="supported_document">
                        <span class="text-danger"> PDF FILE ONLY </span>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-alt-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-alt-success" id="uploadApprovalDocument">
                    <i class="fa fa-check"></i> Submit
                </button>
            </div>
        </div>
    </div>
</div>

// script that used for modal
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    // Trigger data-target modal 
    $('#modal-normal').on('show.bs.modal', function(e){
        var button = $(e.relatedTarget)
        var event = button.data('event')

        var modal = $(this)
        
        // button to click for submit form inside modal
        $('#uploadApprovalDocument').on('click', function(){
            // catch data input file 
            $('#form').submit(function(event){
                var file = new FormData($(this)[0]);
            })
            swal({
                title:"Are you sure this is correct file to submit?",
                text:"Once submit, you can't change the file",
                icon: "warning",
                dangerMode: true,
            })
            .then((willUpload) => {
                if (willUpload) {
                        // if TRUE, send input file to controller based on eventID 
                        $.ajax({
                        url : "{{ url('/club/upload-document-event-club') }}" + '/' + event,
                        type : "POST",
                        data : {'_method' : 'POST', 'supported_document' : 'file'},
                        success: function(){
                            swal({
                                title: "Success",
                                text: "Approval Document has been sent! \n Click OK to refresh the page",
                                icon: "success",
                                }).then(function(){
                                location.reload();
                                });
                        },
                        error : function(){
                            swal({
                                title: "Opps...",
                                text : "Something wrong occured",
                                icon: "error",
                                timer: 1500
                            })
                            }
                        })
                }else{
                    swal("Nothing happens here");
                }
            });
        })
    });
</script>
25 Apr
4 months ago

FareedR started a new conversation Checking Multiple Table For Unique Validation

i separate table by their role. how can i check their email has been taken or not & how can i update same user with same email address ? can i just put ignore('$user->id') ?

'email' => 'required|unique:superadmins,email|unique:admins,email|unique:lecturers,email|unique:students,email',

FareedR left a reply on Validation On Required_if

@BRAUNSON - it works for me , thankyou @braunson ! can i ask you in the same question about image validation on update method ? what if user need to update name and address only but in the form , banner image is there . what should i put in FormRequest? do i need to put input hidden to trigger whether true or false ?

'banner' => 'bail|required_unless=has_file,=,0|mimes:jpeg,png|dimensions:width=1920,height=1080',

23 Apr
4 months ago

FareedR started a new conversation Validation On Required_if

how can i ignore "amount" IF "fee" = 2 ? i keep getting rule for integer on "amount" . do i need to use bail or something else ?

'fee' => 'required',
'amount' => 'required_if:fee,=,1|integer|gte:1',

FareedR left a reply on How To Prevent From This Javascript From Load ?

@CRONIX - it works for me . thankyou @cronix

$(document).ready(function(){
    var start ;
    var end ;
    $('#startDate').on("change",function(){
        start = $(this).val();
        getDate();
    });
    $('#endDate').on("change",function(){
        end = $(this).val();
        getDate();
    });

    function getDate(){
        // if we have start date AND end date value then do ajax inside it
        if(start && end){
            // ajax code here
                $.ajax({
                type : "GET",
                url : "{{ url('club/available-venue-club/start') }}" + '/' + start + '/end/' + end ,
                data :  {'start' : start,'end' : end },
                success : function (data){
                    $('#availableVenue').empty();
                    $.each(data, function(index, venueObj){
                        $('#availableVenue').append('<option value="'+venueObj.id+'">'+venueObj.name+'</option>');
                    });
                } 
            }); 
        }
    }
})

FareedR left a reply on How To Prevent From This Javascript From Load ?

@SAFEMOOD - i put it on $('#endDate') . it is okay ? what if user change startDate only to recheck the venue ?

$(document).ready(function(){
    var start ;
    var end ;
    $('#startDate').on("change",function(){
        start = $(this).val();
    });
    $('#endDate').on("change",function(){
        end = $(this).val();
        $.ajax({
            type : "GET",
            url : "{{ url('club/available-venue-club/start') }}" + '/' + start + '/end/' + end ,
            data :  {'start' : start,'end' : end },
            success : function (data){
                $('#availableVenue').empty();
                $.each(data, function(index, venueObj){
                    $('#availableVenue').append('<option value="'+venueObj.id+'">'+venueObj.name+'</option>');
                });
            } 
        });
    });
})

FareedR started a new conversation How To Prevent From This Javascript From Load ?

input type = date

$(document).ready(function(){
    var start ;
    var end ;
    $('#startDate').on("change",function(e){
        e.preventDefault();
        start = $(this).val();
    });
    $('#endDate').on("change",function(f){
        f.preventDefault();
        end = $(this).val();
    });
    $.ajax({
        type : "GET",
        url : "{{ url('club/available-venue-club/start') }}" + '/' + start + '/end/' + end ,
        data :  {'start' : start,'end' : end },
        success : function (data){
            $('#availableVenue').empty();
            $.each(data, function(index, venueObj){
                $('#availableVenue').append('<option value="'+venueObj.id+'">'+venueObj.name+'</option>');
            });
        } 
    });
})
22 Apr
4 months ago

FareedR started a new conversation Achieve Available Venue On That Date.

i try to achieve "mini stadium" but collection still appear "stadium" and "mini stadium". should i use first() or get() ? or my query are wrong ? anyone can show me ?

database 
Venue
id | name |
1   stadium
2   mini stadium

Venue_has_bookings
id | venue_id | start_date | end_date|
1   1          2019-04-21   2019-04-25

controller
$startDate = 2019-04-21;
        $endDate = 2019-04-25;
        $availableVenue = Venue::with(['bookings' => function ($query) use ($startDate,$endDate){
            $query->where('endDate','>',$startDate)->where('startDate','>',$endDate)
            ->orWhere('endDate','<',$startDate)->where('startDate','<',$endDate);
        }])->get();
        dd($availableVenue);

FareedR started a new conversation How Can Simplify Condition Based On Role

What i want to achieve is

1) Button "unassign as President" only for user has role President
2) Button " unassign as Secretary" only for use has role Secretary
3) If president_id empty , display button "Assign as President" . if user has role Secretary, the button will hide.
4) if secretary_id empty , display button "Assign as Secretary". if user has role President , the button will hide .

Note that, 1 user have one role only . I attached blade view below. The user currently has role as President
@if(!empty($member->club->president_id && $member->student->user->hasRole('president') && !$member->student->user->hasRole('secretary') ))
                            <button type="button" class="btn btn-sm btn-rounded btn-primary" data-toggle="tooltip" title="Unassign as President" onclick="unassignPresident({{ $member->student_id }})">
                                Unassign as President
                            </button>
                        @else
                            <button type="button" class="btn btn-sm btn-rounded btn-info" data-toggle="tooltip" title="Assign as Secretary" onclick="assignSecretary({{ $member->student_id }})">
                                Assign as President
                            </button>
                        @endif
                        @if(!empty($member->club->secretary_id && $member->student->user->hasRole('secretary') && !$member->student->user->hasRole('president') ))
                            <button type="button" class="btn btn-sm btn-rounded btn-primary" data-toggle="tooltip" title="Unassign as President" onclick="unassignPresident({{ $member->student_id }})">
                                Unassign as Secretary
                            </button>
                        @else
                            <button type="button" class="btn btn-sm btn-rounded btn-info" data-toggle="tooltip" title="Assign as Secretary" onclick="assignSecretary({{ $member->student_id }})">
                                Assign as Secretary
                            </button>
                        @endif

https://imgur.com/tZW0efe

21 Apr
4 months ago

FareedR left a reply on Getting "Trying To Get Property Of Non-object" In Blade View.

@SNAPEY - oh okay , thankyou snapey for the info ! i appreciate it !

FareedR left a reply on Getting "Trying To Get Property Of Non-object" In Blade View.

@SNAPEY - i believe that if im using optional, my code would be like this ?

optional($club->president)->name or optional($club->president->name)->id

FareedR left a reply on Getting "Trying To Get Property Of Non-object" In Blade View.

@SNAPEY - i mislooked the code . i should put

@if(!empty($club->president_id))
                        <td class="text-center">
                            <span class="badge badge-primary">{{ $club->president->name }}</span>
                        </td>
                        @else
                        <td></td>
                        @endif

my mistake :(

FareedR left a reply on Getting "Trying To Get Property Of Non-object" In Blade View.

@ASHRAAM - actually in blade i use foreach to list down all the club . sorry for not mention it earlier .

FareedR started a new conversation Getting "Trying To Get Property Of Non-object" In Blade View.

I did test of my relation in laravel tinker . i get what i want . but in blade , i get an error for it . is there anything that i do wrong ?

<td class="text-center">
    <span class="badge badge-warning">{{ $club->president->name }}</span>
</td>
          
Relation in Club Model 
         
public function president()
    {
        return $this->belongsTo(Student::class,'president_id','id');
    }           

FareedR left a reply on How Can I Update Data From Relation ?

@TYKUS - thank you for response ! it works . thanks again . i've been stuck here like 3 hours ..

FareedR started a new conversation How Can I Update Data From Relation ?

how can I set data in club->president_id from member ? in database didnt update but alert appear success .

public function assignPresident($id)
    {
        $role = Role::find(5);
        $member = Member::with('club')->where('student_id',$id)->get()->first();
        $member->club->president_id = $id;
        
        $user = $member->student->user;
        $user->assignRole($role);

        $member->save();

    }