andyandy

andyandy

Member Since 3 Months Ago

Experience Points
8,710
Total
Experience

1,290 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
55
Lessons
Completed
Best Reply Awards
1
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.

Level 2
8,710 XP
Sep
25
2 days ago
Activity icon

Replied to Printing Table Without Knowing Column Names?

Perfect!!! Thank you very much!

Activity icon

Replied to Printing Table Without Knowing Column Names?

@unless($randomTable->empty())
<table>
	<thead>
	<tr>
		@foreach(array_keys($randonTable->first()->getAttributes()) as $cloumnName)
		<th>{{ $columnName }}</th>
		@endforeach
	</tr>
	</thead>
	<tbody>
	@foreach($randomTable as $item)
	<tr>
		@foreach($item->getAttributes() as $value)
		<td>{{ $value }}</td>
		//
		//
		//
		//
		//
		//
		//
		//
		//HOW DO I GET HERE NAME OF THE COLUMN?
		//
		//
		//
		//
		//
		//
		//
		//
		@endforeach
	</tr>
	@endforeach
	</tbody>
@else
No Data
@endunless
Activity icon

Replied to Printing Table Without Knowing Column Names?

Thank you all!

I've tried all solution and decided last one was the best for my purposes.

Activity icon

Started a new Conversation Printing Table Without Knowing Column Names?

I want to do this.

//controller
$randomTable = Articles::orderBy('id', 'desc')->get();

//blade
@forelse($randomTable as $item)

<tr><td>{{$item->id}}</td><td>{{$item->title}}</td><td>{{$item->text}}</td></tr>

@empty
no results
@endforelse

But I want it to auto-detect all columns in table. And print out all available columns.

Activity icon

Replied to Getting Error While Trying To Run "composer Require --dev Laravel/ui"

If I was about to do

composer create-project laravel/laravel someproject

It would still give me Laravel 7, right? How would I go about switching to 8?

Sep
24
3 days ago
Activity icon

Started a new Conversation Getting Error While Trying To Run "composer Require --dev Laravel/ui"

I'm trying to run "composer require --dev laravel/ui" which will result in this error:

https://i.imgur.com/UEpysBj.png

Sep
23
4 days ago
Activity icon

Started a new Conversation Eloquent Modify DB Data Before Comparing Them With Where()

I want to make sure that text is not duplicate. Something like:

$record = Record::where('text', request('text'))->

But I want to strtolower and preg_replace before comparing them. Easy to do on request('text') side:

$record = Record::where('text', preg_replace('/[^a-z0-9]+/u', '', strtolower(request('text'))))->

But ho do I also modify DB data in text column (strtolower + preg_replace) before comparing them? Is that possible?

Sep
22
5 days ago
Activity icon

Replied to Remove ?page=1 From Paginate()

Of course, thank you!

Activity icon

Started a new Conversation Remove ?page=1 From Paginate()

I had this problem:

blah.com/articles //my main article page
blah.com/articles?page=1 //is duplicate with previous page
blah.com/articles?page=2
blah.com/articles?page=3

So i published pagination template and used this preg_replace to remove ?page=1

//previous button link
<a class="page-link" href="{{preg_replace('/\?'.$paginator->getPageName().'=[1]$/','', $paginator->previousPageUrl())}}" rel="prev" aria-label="@lang('pagination.previous')">&lsaquo;</a>

//numbered page links
<li class="page-item"><a class="page-link" href="{{preg_replace('/\?'.$paginator->getPageName().'=[1]$/','',$url)}}">{{ $page }}</a></li>

It worked well, when I was using:

$records->links();

Problem is, it will stop working when I use:

$records->appends(request()->input())->links()
Sep
21
6 days ago
Activity icon

Started a new Conversation Subquery In Eloquent

I'm working with old poorly designed table.

id|name|text|sub_id

I want retrieve all columns + how many times given row ID is set as a sub_id in other rows.

//data in table
1|name|text|0
2|name|text|1
3|name|text|1
4|name|text|1
5|name|text|8

//query retrieves
1|name|text|0|3
2|name|text|1|0
3|name|text|1|0
4|name|text|1|0
5|name|text|8|0


Sep
19
1 week ago
Activity icon

Started a new Conversation Accessor And It's Weird Behaviour

I have column "min_price" and I have created accessor in model:

    public function getMinPriceAttribute()
    {
        return number_format($this->attributes['min_price'], 0, ' ', ' ') . ' $';
    }

And now...

$item->MinPrice //will return value from accessor (expected)
$item->min_price //will also return value from accessor (expected is unchanged value from DB)
Sep
18
1 week ago
Activity icon

Replied to Get Rid Of ?page=1 And Use No-parameter URL Instead As First Page?

Oh, sorry. I realized how stupid that question was and I already deleted it.

Activity icon

Started a new Conversation Get Rid Of ?page=1 And Use No-parameter URL Instead As First Page?

What is the best way to deal with removing ?page=1

blah.com/articles //my main article page
blah.com/articles?page=1 //is duplicate with previous page
blah.com/articles?page=2
blah.com/articles?page=3
blah.com/articles?page=4
blah.com/articles?page=5

Sep
17
1 week ago
Activity icon

Replied to Mysql DATETIME Doesn't Accept High Dates (10+ Years From Now)

By the way, I was creating create/update columns like this:

$table->timestamps();

Should I stop doing that?

Activity icon

Started a new Conversation Mysql DATETIME Doesn't Accept High Dates (10+ Years From Now)

This works:

$record->end_date = '2025-10-16 11:05:00';

But this not:

$record->end_date = '2060-10-16 11:05:00';

I will get:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2060-10-16 11:05:00' for column `records`.`end_date` at row 1 (SQL: insert into `records` (`end_date`) values ( 2060-10-16 11:05:00)
Sep
15
1 week ago
Activity icon

Started a new Conversation Counting Records In Categories And Subcategories

I have tables: CATEGORIES, SUBCATEGORIES, RECORDS (they have expected structure and relationships, record can be in subcategory, NOT category).

I want achieve this:

WEBSITE CATEGORIES AND NUMBERS OF POSTS:

Cars (5):
----AUDI (1)
----BMW (2)
----MG(2)

Animals (2):
----Dogs (1)
----Cats (1)

I can do it easily without counts().

 $something = Category::with('subcategory')->get();

+ in blade foreach() categories and foreach() subcategories in them


But how to do it showing counts of posts?

Sep
14
1 week ago
Activity icon

Started a new Conversation Check If All IDs Exists In Database

Array [1,2,3,4,5,80,90,36,999] - do rows with these IDs exists in DB? Most efficient way?

I need only 'all exists' OR 'there's some problem'.

Sep
13
2 weeks ago
Activity icon

Replied to Help Me Rewrite Eloquent (Query Builder)

And overwriting problem seems to be solved by select('records.*')

return $builder->select('records.*')->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);

I'm marking it solved, although I don't understand this overwriting issue and don't have 100% confidence in this solution.

Activity icon

Replied to Help Me Rewrite Eloquent (Query Builder)

This seems to work.

return $builder->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);

BUT in returned results, second table overwrites columns of first table. Eg. returned ID is not ID of Records (first table) but ID of Cities (second table).

Activity icon

Replied to Help Me Rewrite Eloquent (Query Builder)

In Controller I call:

$records = Record::filteredRecords();
return view('searchResults', compact('records'));

Which refers to function in Model:

public static function filteredRecords()
    {
        return $records = app(Pipeline::class)
            ->send(Record::query())
            ->through([
                \App\Filters\Distance::class,
                ...
                ...
                ...
                ...
                ...
                ...
                \App\Filters\Text::class,
            ])->thenReturn()->paginate(10, ['*'], 'page');
    }

And I want to change only "\App\Filters\Distance::class," which is mentioned in my first post. And my question is about changing that Distance class alone.

Activity icon

Started a new Conversation Help Me Rewrite Eloquent (Query Builder)

I have working script. With table:

RECORDS: id|name|text|latitude|longitude

return $builder->whereRaw('ST_Distance(point(latitude, longitude), point('.request('latitude').','.request('longitude').')) < '.$distance);

But I moved latitude/longitude into separate table, so I have:

RECORDS: id|name|text|city_id

CITIES: id|latitude|longitude

How do I rewrite the query builder?

Sep
11
2 weeks ago
Activity icon

Replied to %LIKE% But Prefer Exact Match

Yeah, I had to do it other way around, since exact match was last. But it works now thanks.

Activity icon

Replied to %LIKE% But Prefer Exact Match

What is this?

where('name', '<>', $data)

<> means !=

?

Activity icon

Replied to %LIKE% But Prefer Exact Match

It won't work.

Imagine searching for VAR, results will be:

abcVAR
deoVAR
VAR
zoaVAR

```

=> exact match won't be first
Sep
10
2 weeks ago
Activity icon

Started a new Conversation %LIKE% But Prefer Exact Match

I have this:

$dbData = City::where('name', 'like', '%'.$data.'%')->limit(10)->get();

I want to prefer exact match on the first place.

Eg. searching for CAT will give CAT on first place and CATegory on second... .

Sep
01
3 weeks ago
Activity icon

Started a new Conversation Help With Combining Two Eloquents

First eloquent which works OK:

$test = Record::select(DB::raw('MAX(id) as id'))->groupBy('region_id')->get();
//1,2,3,4,5,6

Second eloquent which works OK:

$test = Record::select(DB::raw('id, board, region_id'))->whereIn('id', array(1, 2, 3, 4, 5, 6))->get();
//returns data for IDs from array

NOW I COMBINE them together and it doesn't work

        $test = Record::select(DB::raw('id, board, region_id'))->whereIn('id', function ($query) {
            $query->select(DB::raw('MAX(id) as id'))->groupBy('region_id');
        })->get();
//returns entire table
Activity icon

Replied to Select From MySQL One Record Per Unique Column

If I want more data from the row, it works in raw query.

SELECT board, region_id, MAX(id) as id FROM `records` GROUP by region_id

But in Laravel version it doesn't, it throws "board isn't in GROUP BY "

 Record::select(DB::raw('board, region_id, max(id) as id'))
            ->groupBy('region_id')
            ->get();
Activity icon

Replied to Select From MySQL One Record Per Unique Column

But it will give me all users to that city, right? I have 15 000 users...

And I need just highest ID.

Aug
31
3 weeks ago
Activity icon

Started a new Conversation Select From MySQL One Record Per Unique Column

I have table users.

ID - NAME - CITY

I want show all unique cities and latest user from each of them.

Aug
29
4 weeks ago
Activity icon

Replied to ST_Distance_Sphere Does Not Exist

Yeah... 10.4.8-MariaDB

Activity icon

Replied to Blade Variable Inside Script Tag, VSCODE Goes Crazy

It was just an Beauty Blade extension going crazy. There is nothing wrong with putting blade variables into script tags.

Activity icon

Started a new Conversation Blade Variable Inside Script Tag, VSCODE Goes Crazy

I have this blade template

<h1>some html</h1>
<script>
$(function () {
         $('input[name="datum"]').daterangepicker({
         minDate: moment(),
        })
}
</script>

I want to put some blade logic about MINDATE, like this:

<h1>some html</h1>
<script>
$(function () {
         $('input[name="datum"]').daterangepicker({
         minDate: {{ $datumData['startDate'] ? $datumData['startDate'] : moment() }},
        })
}
</script>

But when I try to SAVE this my VSCODE text editor goes all crazy and converts it into

<h1>some html</h1>
<script>
$(function () {
         $('input[name="datum"]').daterangepicker({
         minDate: {
                                        {
                                            % 24 datumData % 5 B % 26 % 2339 % 3 BstartDate % 26 % 2339 % 3 B % 5 D % 20 % 3 F % 20 % 24 datumData % 5 B % 26 % 2339 % 3 BstartDate % 26 % 2339 % 3 B % 5 D % 20 % 3 A %
                                                20 moment()
                                        }
                                    },
        })
}
</script>

What to do?

Aug
28
4 weeks ago
Activity icon

Replied to ST_Distance_Sphere Does Not Exist

My XAMPP control panel says I'm using MySQL (which supports this function), but info files about my XAMPP mentions I'm using MariaDB, which doesn't support this.

Activity icon

Started a new Conversation ST_Distance_Sphere Does Not Exist

I want to display results that are within $distance (GPS coordinates).

<?php

namespace App\Http\Controllers;

use App\Record;

class SearchResultsController extends Controller
{
    public function search()
    {

        $lon = 0;
        $lat = 0;
        $distance=1000000;
        return Record::whereRaw('ST_Distance_Sphere(point(latitude, longitude),POINT('.$lat.','.$lon.')) < '.$distance)->get();

        
    }
}

But I'm getting ERROR:

SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION database.ST_Distance_Sphere does not exist (SQL: select * from `records` where ST_Distance_Sphere(point(latitude, longitude),POINT(0,0)) < 1000000)

I don't know what to try anymore.

Aug
27
1 month ago
Activity icon

Replied to How Do You Populate MySQL Tables On Server?

It seems like a seeder is a function for a testing purposes, to generate random data? Or can it be used to populate DB with real data? Eg. insert 100 000 cities with their zip codes that I have available in localhost DB?

Activity icon

Started a new Conversation How Do You Populate MySQL Tables On Server?

I can run "php artisan migrate" on the server to create all tables (eg zip codes table). But how do I populate these tables with data (eg actual zip codes and cities)? Given you have as entry points console + pulling script from Github. Not phpmyadmin or remote access to mysql.

Aug
19
1 month ago
Activity icon

Started a new Conversation What Is Validating Register/login Form (js)?

I just installed AUTH. And if I don't fill some input during registration/login I will get javascript popup "Please fill in this field." (with yellow exclamation mark icon)

Where is this coming from? I want to translate it. But searching all Laravel files I couldn't find phrase "Please fill in this field."

Aug
11
1 month ago
Activity icon

Replied to Classic Login And Passport Login At Same Time

You wanna tell me that when JS sends a request, Laravel can attach a cookie to this request?

Is that even possible to backend application was somehow editing my request coming from frontend application? That seems impossible to me.

When my front end React sends request (headers + some JSON) how could even backend attach something to it. It just waits to consume it when it reaches it. It can't edit requests content.

Aug
10
1 month ago
Activity icon

Replied to Classic Login And Passport Login At Same Time

I can't understand from the manual how it is supposed to help with my problem. Would it solve this problem (required double login)?

  1. I want login into administration via standard web form. And do some standard stuff. For this part I would be authenticated via regular login form. No problem.

  2. BUT in one part of administration I would like to use React (javascript application), which would get data from server via GET request on API. And then send data to server via POST API request. To do any of that I would have to again login - this time via API to the passport. To get my secret token. (I wouldn't be working with public data, but sensitive data belonging to that account)

Activity icon

Started a new Conversation Classic Login And Passport Login At Same Time

I want to login into a web-admin via standard login form.

But in the admin I want to make API calls. Which need passport login token. Is there some standard solution to this or how to approach it?

Jul
24
2 months ago
Activity icon

Started a new Conversation How To Use Imagejpeg() In Laravel?

I can use this to upload image directly:

$path = $request->file('image')->store('public/img/200x200');

I want to first resize image in PHP and than store it with:

imagejpeg($thumb, '../storage/app/public/img/200x200/asd.jpg', 80);

Which seems to work. But it obviously doesn't generate file name. Is it even a correct way? Could I somehow join Laravel store() method and imagejpeg()?

Jul
14
2 months ago
Activity icon

Replied to How To Create A Simple Eloquent Function?

Thank you. That's exactly what I was looking for.

Activity icon

Replied to How To Create A Simple Eloquent Function?

The ban is giving me "Too few arguments to function, 1 passed 2 expected". I don't really know what to pass as a $query?

Activity icon

Started a new Conversation How To Create A Simple Eloquent Function?

After many failed attempts I need asistence. In my controller I would like to call for example ban(5), which would ban user 5. Or morningSummary() which would retrieved data from logs table created during 5pm - 6am.

Even a link to tutorial would do it. I can't find any. I'm not looking for Repositories, as it seems to be an overkill for this.

Jul
12
2 months ago
Jul
11
2 months ago
Activity icon

Started a new Conversation API Resources - Resource Collections - Pagination Meta Data Disappear

I'm studying this https://laravel.com/docs/5.7/eloquent-resources

This code will return 5 articles + pagination meta data (current page, last_page etc.)

        $publications = Publication::paginate(5);
        $publications = PublicationResource::collection($publications);
        return $publications;

Great.

Now I will generate resource for controlling collections of models. And allows me add some extra metadata into response. (author, version, date)

        $publications = Publication::paginate(5);
        $publications = new PublicationCollection(PublicationResource::collection($publications));
        return $publications;

Which works. I will get 5 articles + my extra meta data.

BUT pagination data are gone. And no matter what I try I can't get pagination meta data back.

Activity icon

Replied to Eloquent BelongsTo: Put Child At Same Level As Parent

Ok, it worked. But instead of:

'category_name' => $this->when($this->relationLoaded('category'), fn() => $this->category->name),

I had to use:

'category_name' => $this->when($this->relationLoaded('category'), function() { return $this->category->name; } ),

Otherwise I would get:

syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' 

I'm on PHP 7.3.11

Activity icon

Replied to Eloquent BelongsTo: Put Child At Same Level As Parent

Oh, wow. I didn't know about API resources yet. Thank you.