Miko55

Miko55

Member Since 7 Months Ago

Experience Points 1,520
Experience Level 1

3,480 experience to go until the next level!

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

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

20 Apr
2 days ago

Miko55 left a reply on Laravel Variables From Controller To View

@TYKUS - Okey that was pretty easy :D

Well I also used this function that returns status after sent email for password reset:

protected function sendResetResponse(Request $request, $response)
    {
        return redirect($this->redirectPath())
                            ->with('status', trans($response));
    }

And here I needed to use session to access status value. If I can ask, where is the difference now?

Miko55 started a new conversation Laravel Variables From Controller To View

I am modifying the return function of password reset, when user click on link provided in email.

Now I have this:

return view('welcome')->with(
            ['token' => $token, 'email' => $request->email, 'recovery => 'password']
        );

I have problem with access to these variables. I tried to print them like with {{session('recovery')}} but nothing happens. I managed to print token out with {{$token}}, but what I need is recovery variable.

17 Apr
5 days ago

Miko55 started a new conversation Laravel Passport Cookie Expire

I have authorization done by consuming API with Javascript, so with cookie. Now I wonder how to set expire? If I close browser and come back I am still logged, only way that I destroy cookie is to logout or clear sessions and cookies.

15 Apr
1 week ago

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - Thank you for your help

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - So is this safe to use ?

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - That didn't help, but I found solution. I added Passport::withoutCookieSerialization(); into boot method in AppServiceProvider.

Not sure what this changes,but now it works

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - Windows OS and XAMP . I also tried with php artisan serve and still same issue

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - I did that and CSRF and XSRF tokens are included in headers

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - Only this:

message Unauthenticated.

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - I removed it form my request, but still not working.

test(){
                let vm=this;
                axios({ method: 'GET', 
                        url: '/api/test',
                        params: {},
                    }).then(function (response) {
                        console.log(response);
                    }).catch(function (error) {});
            },

14 Apr
1 week ago

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - I know that I don't need this, this was just one of countless tries. I am not sure what exactly you mean by stateless requests and web requests.

But now I ran php artisan make:auth and logged user from login page that was crated and I can see laravel_token. So I show Vue component if user is logged in, but API calls from that component still return Unauthenticated.

13 Apr
1 week ago

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - I am using Vue and making calls with axios. Now I made a fresh app and still not working. Bellow is my code:

AuthController

public function test(){
        return "test";
    }

    public function login(Request $request){
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->accessToken; 
            return response()->json(['success' => $success]); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }

    public function register(Request $request){
        $user = User::create([
            'name' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
    }
Route::middleware(['auth:api'])->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });

    Route::get('/test', '[email protected]');
    
});

Route::post('/login','[email protected]');
Route::post('/register','[email protected]');

Now for test I am getting Error: Unauthenticated. And this are headers

Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  XSRF-TOKEN=eyJpdiI6Im5kbmZHb0R…mYzlhMjYxOGIzOTViMWI1MzMwOSJ9
Host    funbet.test
Referer http://funbet.test/
User-Agent  Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/66.0
X-CSRF-TOKEN    X7eHgRctYLxCM2CDTqZJyb35tYp7h0IblRalPTIO
X-Requested-With    XMLHttpRequest
X-XSRF-TOKEN    eyJpdiI6Im5kbmZHb0RXTElNek9Qaj…kMWJlMzViNDZiOTY5M2MzNGRjIn0=
11 Apr
1 week ago

Miko55 left a reply on Laravel Passport Correct Usage

@TOKOIWESLEY - Yes, I added CreateFreshApiToken and I am have X-Requested-With in my header in axios, but I still don't get laravel_token

09 Apr
1 week ago

Miko55 started a new conversation Laravel Passport Correct Usage

Right now I have most things working as I am storing access token in localStorage. But now I want to move this to Cookies. For now I had only auth:api in my routes and after adding web middleware I am getting also laravel_session ans XSRF-TOKEN in cookies.

Now I removed auth:api because I still needed to send Bearer token, but with only web middleware I can make requests without any authorization from Postman. So what would be correct setup to use Cookies properly?

08 Apr
2 weeks ago

Miko55 started a new conversation Foreign Key To Unique Composition

So I have to tables: Leagues and Teams.

Schema::create('teams', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('sport_id')->unsigned();
            $table->integer('league_id')->unsigned();
            $table->integer('teamID')->unsigned(); //->unique();
            $table->string('name');
            $table->string('shortName');
            $table->string('crest')->nullable();
            $table->timestamps();

            $table->unique(array('league_id', 'teamID'));

            $table->foreign('sport_id')->references('id')->on('sports')->onDelete('cascade')->unsigned();
            $table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade')->unsigned();
        });
Schema::create('matches', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('gameID')->unsigned(); //->unique();
            $table->integer('league_id')->unsigned();
            $table->integer('team1_id')->unsigned();
            $table->integer('team2_id')->unsigned();
            $table->integer('team1goals')->nullable();
            $table->integer('team2goals')->nullable();

            $table->unique(array('league_id', 'gameID'));

            $table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade')->unsigned();
            $table->foreign('team1_id')->references(array('league_id', 'teamID'))->on('teams')->onDelete('cascade')->unsigned();
            $table->foreign('team2_id')->references(array('league_id', 'teamID'))->on('teams')->onDelete('cascade')->unsigned();
        });

Now I needed to create unique pairs as I am getting teams and games IDs from different APIs and they could overlay. But now I can't create foreign key to teamID in matches table, because teamID is not unique. That's because I need to have a unique pair.

Question now is how can I have a foreign key referenced to unique pair, in this case to league_id and teamID?

11 Feb
2 months ago

Miko55 left a reply on Laravel Passport Refresh Token

@NEE - Well to save it into local storage with access token together would be a security issue. I wan thinking if I need to save it into DB or is there a way to get it later, for example after 3days when I would like to refresh users access token?

10 Feb
2 months ago

Miko55 started a new conversation Laravel Passport API With Javascript

Till now I was storing access token in local storage. Now I want to move it into cookies.

So I added \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, into Kernel.php. I also changed my axios call:

    axios.get('/forum', {
        params: {
          filterBy: vm.filterBy,
          filterDirection: vm.filterDirection,
          theme: vm.theme
        },
        withCredentials: true,
        headers: {
          //'Authorization': 'Bearer ' + this.getToken,
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRF-TOKEN':window.Laravel.csrfToken
        }
      }).then(function (response) {
        vm.posts=response.data
      }).catch(function (error) {}); 

You can see that I commented Authorization header where I was sending access token from local storage. I see that CSRF token is added in request header and that access token is saved in X-XSRF-TOKEN. There is also a Cookie with value: XSRF-TOKEN: (token value).

Now I am getting error with: Route[login] not defined.

Perhaps problem is that in Cookie value there is XSRF-TOKEN instead of laravel_token ?

09 Feb
2 months ago

Miko55 started a new conversation Laravel Passport Refresh Token

I have my login set up with Passport. I successfully get access_token and have it stored in local storage.

But I have a problem getting refresh token. I am not saving that into local storage for security reasons, so when I want to refresh access_token, how can I get a refresh token?

One way is probably to create new table with user_id, access_token and refresh token. Is that a correct solution or is there another way?

Miko55 started a new conversation Laravel Authentication "standard"

I am using Laravel and Vue. I have Passport set up. I login with user, send API to back-end and get access token back. I store access token into local storage and later on use it in headers when making API calls. I changed expire duration to 1 day.

Now what I am interested into is how to handle expire date? I know that API calls stop working after expire date, but how to know that expire date is past and to delete it from local storage, redirect user back to login? Or should I somehow refresh tokens?

I don't want users getting empty pages as API stops working or have them fill out certain form and not get their data committed.

05 Feb
2 months ago

Miko55 left a reply on Inner GroupBy On Collection

@AURAWINDSURFING - Lets say I have something like this:

ID | player1_id | player2_id | scoreP1 | score P2 | stage

1 | dummy1 | dummy2 | 2 | 3 | ROUND16

2 | random2 | test1 | 2 | 1 | ROUND16

3 | dummy2 | dummy1 | 1 | 1 | ROUND16

4 | test1 | random2 | 2 | 3 | ROUND16

5 | random2 | dummy2 | 1 | 1 | ROUND8

6 | dummy2 | random2 | 1 | 3 | ROUND8

And end result that I want:

ROUND16{

[0]{

[id:1,player1_id:dummy1,player2_id:dummy2]

[id:3,player1_id:dummy2,player2_id:dummy1]

}

[1]{

[id:2,player1_id:random2,player2_id:test1]

[id:4,player1_id:test1,player2_id:random2]

}

}

ROUND8{

[0]{

[id:5,player1_id:random2,player2_id:dummy2]

[id:6,player1_id:dummy2,player2_id:random2]

}

}

With your code I would get groups ROUND16,ROUND8 etc. but not inner ones

Miko55 left a reply on Inner GroupBy On Collection

@AURAWINDSURFING - I listed only ROUND_OF_16 as currently there is no progress yet. But there will be ROUND_OF_8 and so on.

My bad, I should add other ones.

Miko55 started a new conversation Inner GroupBy On Collection

I have table with matches between players, with fields:

ID | player1_id | player2_id | scoreP1 | score P2 | stage

Now value for stages are ROUND16, ROUND8, ROUND4, ROUND2, FINAL. Those value represent stages of a tournament. Now I group matches into groups for each stage. Each match between players happens twice, once player is "home" and other time "away". For example player Dummy would once be under player1_id other time under player2_id.

Now what I want to do is to group those two matches together under a group ROUND16. So I would get groups for rounds and inside groups with paired matches. Problem is that player is one time under player1_id and other time under player2_id so I can't figure out how to group this two matches together.

This is how I group matches into groups of stages.

$matches=Match::where('stage','ROUND_OF_16')->get();

$stages = $matches->mapToGroups(function ($item, $key) {
                    return [$item['stage'] => $item];
                });
03 Feb
2 months ago

Miko55 left a reply on Laravel - Php Artisan Serve API Problem

I solved it, it was problem with CORS

02 Feb
2 months ago

Miko55 started a new conversation Laravel - Php Artisan Serve API Problem

I deploy my site with php artisan serve and I have a login form in Vue. So I use axios to make an API call. Instead of GET request I get OPTIONS method. Why is this happening ?

01 Feb
2 months ago

Miko55 started a new conversation Laravel And Vue Deplyoment

So I made my project with Laravel-mix. I have back-end done with Laravel and front-end with Vue. For now I have my project hosted with XAMPP. Where I setup virtual host and changed hosts file under system32, so I access my site on URL myapp.test

Now I wanted to access my site from other devices in LAN and when I go to public folder welcome.blade loads but Vue components don't unless I access my site myapp.test. So why is that?

My welcome.blade

<body>
    <div id="app">
        @csrf
        <router-view class="view one" name="nav"></router-view>
        <router-view class="view two" name="con" style="margin-top:2%"></router-view>
    </div>

    <script src="{{asset('js/app.js')}}"> </script>
</body>

Now other things that I am having problem is, building my Vue part. I want to run npm run build but I get error that script is missing. I understand that this is because it's missing from package.json script array, but I am not sure how to add it and what to put under build key.

With all of that I am wondering if it was a good idea using laravel-mix and should I separate Vue and Laravel? Specially wondering that when I will get to deplyoment.

25 Jan
2 months ago

Miko55 started a new conversation Laravel Passport And JWT

I am using Vue for front-end and Laravel for back-end. I have my registration and login set up with Laravel Passport. I also save access token in local storage for future use. Now I have some API calls to get some posts for forum etc.

All of those API call require that I sent authorization header. In that header I am using Bearer: (access_token). For access_token I am using one that I got when I logged in. What I want to know is that right way? Or should I use some other library to generate JWT? Is access_token already a JWT?

This is my first big project with Laravel and I am a bit confused. I would appreciate some explanation.

23 Jan
2 months ago

Miko55 left a reply on Eloquent GroupBy Returns Only First Row Of Each Group

@VILFAGO - This gives me right results, mind explaining how this work?

And if it's possible if name of groups are not actual dates, but would be [0],[1] etc. or something like that?

Miko55 started a new conversation Eloquent GroupBy Returns Only First Row Of Each Group

I want to get matches from my table, so that I would get groups that would contain matches that start at the same date.

Matches table:

id | team1_id | team2_id | team1goals | team2goals |

1 | 51 | 62 | 2 | 1 | 2018-08-10 21:00:00

2 | 12 | 31 | 1 | 1 | 2018-08-10 21:00:00

Currently I have this:

$matches=Match::where('season_id',1)
                        ->where('league_id',1)
                        ->where('matchday',20)
                        ->where('status','SCHEDULED')
                        ->with('team1:teamID,shortName','team2:teamID,shortName')
                        ->groupBy('startDate')
                        ->get();

This returns me four groups, and this is right as there are 4 different date. But I only get first match in that group, but there should be two, three or four matches per date. So how could I get all the matches for each group ?

22 Jan
3 months ago

Miko55 started a new conversation Eloquent Foreign Table With Only Specific Column

I have Teams table and Matches.

Teams table: id teamID name shortName crest 1 51 Liverpool FC Liverpool liverpol.jpg

Matches table: id team1_id team2_id team1goals team2goals 1 51 62 2 1

class Team extends Model
{
    public function matches(){
        return $this->hasMany(Match::class);
    }
}
class Match extends Model
{
    public function team1(){
        return $this->belongsTo(Team::class,'team1_id','teamID');
    }

    public function team2(){
        return $this->belongsTo(Team::class,'team2_id','teamID');
    }
}

Now when I am getting Match I want to change id of the teams in it, with short name from the Team table.

$matches=Match::where('season_id',151)
                        ->where('league_id',1)
                        ->where('matchday',24)
                        ->where('status','SCHEDULED')->get();

foreach($matches as $m)
{
      $m->team1name=$m->team1->shortName;
}

This does add a field with name team1name and with right value, but I also get a field with team1 name and with all the properties of that team.

I also tried with eager loading like this

 $matches=Match::where('season_id',151)
                        ->where('league_id',1)
                        ->where('matchday',24)
                        ->where('status','SCHEDULED')->with('team1:shortName')->get();

But that way I get null.

So how can I get only shortName for the team that is selected Match?

19 Jan
3 months ago

Miko55 left a reply on Can't Get Property From Realtionship Table

@VILFAGO - Great, I didn't know about this as I am still new to Laravel. One more things, I am trying to get only sportName without it's id, is that possible? If I try to to get just that I get null, but if I add id I get value for sportName but also for it's id.

$filteredScoresSport = Score::select('sport_id',DB::raw('SUM(points) as points'))
                                    ->where('user_id',$id)
                                    ->groupBy('sport_id')->with('sport:sportName')->get();

This gives me null.

Miko55 left a reply on Can't Get Property From Realtionship Table

@VILFAGO - ``` $filteredScoresSport = Score::select('sport_id as sportName',DB::raw('SUM(points) as points')) ->where('user_id',$id) ->groupBy('sport_id')->get();

Miko55 started a new conversation Can't Get Property From Realtionship Table

I have two tables. First one is Sports:

id sportName 1 Football

And second one is Scores:

id sport_id points 1 1 25

And for my models.

class Score extends Model
{
    public function sport(){
        return $this->belongsTo(Sport::class,'sport_id');
    }
}
class Sport extends Model
{
    public function scores(){
        return $this->hasMany(Score::class);
    }
}

Now when I loop through scores

foreach($filteredScoresSport as $score)
        {
            $a=$score->sport->sportName;
            return json_encode($a);
        }

I get error: Trying to get property sportName' of non-object

What I am doing wrong? I can't seem to find mistake

08 Nov
5 months ago

Miko55 left a reply on Laravel Email Confirmation With Vue

@THET - But when/where exactly email sending is called ?

07 Nov
5 months ago

Miko55 left a reply on Laravel Email Confirmation With Vue

@THET - I know this might look like I am not putting any work into, but I didn't get it to work. I didn't know about that function so I explored a bit, I found: https://stackoverflow.com/questions/52362927/laravel-email-verification-5-7-using-rest-api and tried with that, but failed to implement :(

Miko55 left a reply on Laravel Email Confirmation With Vue

Thing is with sending the mail. If you do it as on documentation, then you already have a site which sends the email. Now with Vue you don't have this site and I am not sure where to include middleware etc.

Miko55 started a new conversation Laravel Email Confirmation With Vue

I am using Vue as front-end and Laravel as back-end. I have set up registration, login and authentication with Laravel Passport. Now I want to add email confirmation. I know that Laravel 5.7 has this feature, but as I am using Vue and routing is done with Vue router, I can't really follow the documentation. I couldn't find any guide to combining those two so I wonder is that even possible to do or should I take a look at some other tool, perhaps do my custom email confirmation?

With email confirmation I mean sending a confirmation/activation link to user after registration.

28 Oct
5 months ago

Miko55 started a new conversation Request Validation

I can't figure out why my validation doesn't work. I already have it on users and it work fine but I can't figure it out for forum posts.

I have really simple validation just to get it working.

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:100|unique:forum_posts',
        ]);

        return json_encode("valid");
    }

And my axios request

    axios.post('/forum', {
            params: {
                title: vm.title,
                content: vm.content,
                theme: vm.theme
            }
            }).then(function (response) {
                console.log(response)
            }).catch(function (error) {});

Even if I fill out title and I can see that is set under Network and opening request I still get error: "The title field is required."

29 Sep
6 months ago

Miko55 started a new conversation One To Many Realationship With Where Query

I have two tables, one is Scores and other one is Leagues.

In Leagues I have ID, LeagueName

In Scores I have ID, league_id, user_id, points

class League extends Model
{
    public function scores(){
        //return $this->hasMany(Score::class,"user_id","id");
        $this->hasMany(Score::class,'league_id');;
    }
}
class Score extends Model
{
    public function user(){
        return $this->belongsTo(User::class,'user_id');
    }

    public function league(){
        return $this->belongsTo(League::class,'league_id');
    }
}

This two are my models. Now I want to make a Eloquent query where I would filter Scores by LeagueName. I tried bunch of things, but they didn't work.

23 Sep
6 months ago

Miko55 started a new conversation Adding Number Row

I have users sorted by their points and now I would like to add a column with row numbers from 1 to N, where N is number of users. Is that possible?

$scores=DB::table('scores')->join('users', 'users.id', '=', 'scores.user_id') 
                                        ->join('sports', 'sports.id', '=', 'scores.sport_id')
                                        ->join('leagues', 'leagues.id', '=', 'scores.league_id')
                                        ->where('users.username','LIKE',"%{$request->filter}%")
                                      ->select('users.username','points','sports.sportName','leagues.leagueName')
                                        ->orderBy($request->sort, $request->direction)->paginate(4);
02 Sep
7 months ago

Miko55 left a reply on Raw SQL Query With Variable As Data

Okey solved it with ->addIndexColumn()

Miko55 left a reply on Raw SQL Query With Variable As Data

I mean that when I order user by their points there would be another row with numbers from 1 to user count(). So user with most points would have row number 1 etc. In Microsoft SQL there is a function, for MySQL here is a explanation: http://www.mysqltutorial.org/mysql-row_number/

Miko55 left a reply on Raw SQL Query With Variable As Data

I made it work by using explode(',',$sport_id) instead of array. I was using raw SQL because I wanted to create row numbers, any idea how I could make that work with Eloquent ?

Miko55 left a reply on Raw SQL Query With Variable As Data

Well I changed my query to:

$scores=DB::table('scores')->join('users', 'users.id', '=', 'scores.user_id') 
                                       ->join('sports', 'sports.id', '=', 'scores.sport_id')
                                       ->join('leagues', 'leagues.id', '=', 'scores.league_id')
                                       ->whereIn('scores.sport_id',array($sport_id))
                                       ->select('users.username','points','sports.sportName','leagues.leagueName')->get();                  
            return json_encode(( ['data' => $scores] ));

But it's same result. But if I put for example [1,3] instead of variable I get right results. So I think problem is in variable

Miko55 started a new conversation Raw SQL Query With Variable As Data

I have SQL query with WHERE IN statement where I use variable that I pass by ajax data. The value of variable is fine, I check that under network and also by simply returning it back. So the value of variable is for example "1" or "1,3". It works fine if I execute query on phpmyadmin and it works when there is only one number like "1", but when there are two it doesn't work, response is empty data.

    $scores=DB::select("SELECT user.username, points, sport.sportName
                                          FROM scores
                                          JOIN users AS user ON user.id = scores.user_id
                                          JOIN sports AS sport ON sport.id = scores.sport_id
                                          WHERE scores.sport_id IN (:sport_id)
                                          ORDER BY points DESC",array('sport_id' => "$sport_id"));  
    return json_encode(( ['data' => $scores] ));
01 Sep
7 months ago

Miko55 started a new conversation Nest JSON

I am currently return JSON in this format:

[ {"username":"test3","points":62,"sportName":"Basketball"}, {"username":"test2","points":55,"sportName":"Football"}, ]

But i would need it to be like:

{ "data":[ { "username":"test3", "points":"62", "sportName":"Basketball" }, { "username":"test2", "points":"55", "sportName":"Football" } ] }

This is not constant data, data that I return I get like this:

    $scores=DB::select("SELECT user.username, points
                        FROM scores
                        JOIN users AS user ON user.id = scores.user_id
                        ORDER BY points DESC");

    return json_encode($scores);

Miko55 started a new conversation Datatables Static Row At Bottom

I have leaderboards with usernames and their points. There is pagination every 10users. First three users have custom classes so they are colored gold/silver and bronze. Now what I want to do is to have a static row at bottom for example and in that row currently logged in user would be shown, his place, username and points. Places are made with index column. So how should I approach this ?

30 Aug
7 months ago

Miko55 left a reply on Database Realtionships

Where should I put

    public function $appends = ['username'];

If I out it into Score Model I get syntax error, unexpected $appends

Miko55 started a new conversation Database Realtionships

I have users table and scores table. In user table there are typical fields like username, email, password etc. in scores I have field with user_id and points. Now I am showing table with DataTables like this (using ajax):

    $query = DB::table('scores');
        return DataTables::of($query)->make(true);

And then I show it in table. But I want to replace user_id with actually username. How I should do that? Should that be done with Models or with join statements. I am new to Laravel and I am not sure what the best way would be

29 Aug
7 months ago

Miko55 left a reply on Datatables Not Applaying To The Table

EDIT: I think it was problem in my Routes as both have 'leaderboards'. But if I change second one to something else then I get errors. First one: [Vue warn]: Error compiling template: Second one: TypeError: $(...).Datatable is not a function

Miko55 started a new conversation Datatables Not Applaying To The Table

I am trying to show my data from database in table. I have this so far: -between tags: ​`` ​<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css"> ?my web.php ​``` Route::get('leaderboards', '[email protected]');

Route::get('leaderboards', ['as'=>'get.data','uses'=>'[email protected]']); ​`` In PagesController ?ublic function leaderboardsData() { return DataTables::of(User::query())->make(true); }

public function leaderboards()
{
    return view('pages.leaderboards');
}

`` And in my leaderboards.blade.php ?extends('layouts.app')

@section('content')

Leaderboards!

Id Name Email Created At Updated At
<script>
    $(function() {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{!! route('get.data') !!}',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'created_at', name: 'created_at' },
                { data: 'updated_at', name: 'updated_at' }
            ]
        });
    });
</script>

@endsection ​```

When I go to leaderboards page I do get results from query, but it's in JSON format and is not shown in table. How can I fix that?