Axeia

Axeia

Member Since 2 Years Ago

Experience Points 980
Experience
Level
Lessons Completed 1
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

09 Dec
1 week ago

Axeia left a reply on Publish/Deploy Site - Best Practices?

I did go with a git pull, however trying to optimize it further by putting the vendors folder in the .gitignore and then running composer install on the server gives me a 500 Internal Server Error. I've no idea what is causing it and the helpdesk of the host tells me there is no error logs that would explain what is causing this. (definitely can't find any error log myself).

So I guess I'll go back to having /vendors/ included in my git repository - it seems to be choking things though as commands such as git status take a long time to execute.

08 Dec
1 week ago

Axeia left a reply on Publish/Deploy Site - Best Practices?

Laravel forge definitely sounds like a no-messing about solution, not to mention it supports laravel to boot! But I am messing about and doing things as cheap as possible so sadly it's not the solution for me in this case.

For now from what I've described earlier I've done step 1 and doing step 2 manually as I think git pull in my script is choking on the password prompt. Still - it's a heck of a lot faster than uploading things manually through WinSCP :) and with enough dedication/time Step 2 and 3 could probably be made to work. I found this [url=http://abhisheksachan.blogspot.com/2014/04/setting-up-godaddy-shared-hosting-with.html]article for example[/url] which seems to do pretty much that.

Axeia left a reply on Publish/Deploy Site - Best Practices?

Thank you all I ended up putting my project on bitbucket in a private repository. However getting it to the server would be a lot easier if I could use git pull if you don't mind me asking @primordial why would this be such criminally bad practice.If it helps - I'm the only developer so I know exactly what would get pushed/pulled.The easiest/most streamlined way to proceed from here (in my eyes at least) would be

  1. Create a symlink from the shared hosts "public_html" folder to laravels "public" folder
  2. Create a (PHP) script on the webserve that does a "git pull" to update everything and run migrations
  3. Create a webhook on bitbucket that after receiving a push calls the PHP script from step 2. What would the alternative be for the git pull? Because I can only think of solutions that would download a bunch of unchanged files resulting in longer wait times and lots of network traffic. I am however very new to git.
06 Dec
1 week ago

Axeia started a new conversation Publish/Deploy Site - Best Practices?

Hello,

I've developed a site using Laravel and I'm finally ready to deploy it to the live (shared) server. I've currently just uploaded everything through sftp (with WinSCP), exported/imported the database. Put laravels /public / folder in the servers public_html/ folder and fixed anything that broke due to environment changes (different MySQL versions). So basically I did what this video by Traversy Media also tells you to do: https://www.youtube.com/watch?v=6g8G3YQtQt4

However uploading a new version is a bit of a nightmare, simply dragging the folders over in WinSCP and applying what database changes are needed takes a long time, surely there must be a faster way to do this? Just the file uploading can take 20 minutes. Zipping things up and then unzipping it through the cpanel takes less time to upload but adds additional steps slowing things down.

Tools at my disposal: A linux (openSUSE) local server that stores the files and acts as the local webserver that I have full access to, my own Windows 10 desktop. And I can connect to the remote shared host/server through WinSCP (FTP/SFTP), putty, cpanel.

29 Nov
2 weeks ago

Axeia started a new conversation Query Bug Workaround - The Correct Way To Do It?

Hello, I have a query that on my live server (but not on the test server - yeah that's confusing) throws a "General error: 1615 Prepared statement needs to be re-prepared" after some Googling people seem to get around this by adding this to config/database.php

    'options'   => [
        \PDO::ATTR_EMULATE_PREPARES => true
    ]

This however brings some some [url=https://michaelseiler.net/2016/07/04/dont-emulate-prepared-statements-pdo-mysql/]security concerns[/url] with it. So instead what I did was put this around my query (that I know to be safe as it only uses values already validated and in the database.


            $pdo = \DB::connection()->getPdo();
            $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);

           //Query :)

            $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

I'm just kinda wondering why no one else seems to have done this, wouldn't this be the smarter/saver way to do it?

Axeia left a reply on Laracasts Refresh

HTML in the attribute doesn't display properly, it seems to undergoing a double round of encoding? Perhaps both when storing and retrieving?

My post over here (https://laracasts.com/discuss/channels/eloquent/sync-with-additional-values-cant-wrap-my-brain-around-it) has the following HTML (I'll just post an image as formatting that in this post would get confusing): https://puu.sh/C9O0F/d72c54ad40.png

23 Nov
3 weeks ago

Axeia left a reply on ->sync With Additional Values - Can't Wrap My Brain Around It

Looks like I made this thread in vain, cleaning up the code elsewhere after a good night of sleep made sync work with an array of:

$trainer->shinyPokemons()->sync(
  ['pokemon_icon_001_00_shiny.png' => ['gender' => 1]
  ['pokemon_icon_001_00_shiny.png' => ['gender' => 1]
)

My thanks however to both of you for thinking along :).

21 Nov
3 weeks ago

Axeia left a reply on ->sync With Additional Values - Can't Wrap My Brain Around It

@SHEZ1983 - >if you want to sync then you first need to create a shinyPokemon so: I'm good in that regard, the Pokemon exists, the file_names exist, the relationships are properly defined (e.g. $trainer->shinyPokemons() returns the expected values). It's just the inserting that's proving to be difficult within eloquent.

sync is used when you already have existing and u neeed to pass in IDs.. Aye I did want to use the full functionality of sync, but hey if 'create works' I don't mind doing a delete on shinyPokemons for the matching trainer name first.

Sadly create fails which I think is due the composite primary key.

You'll have to use attach() and detach() instead. Going by the documentation it looks like it takes the exact same parameters and thus would run into the exact same problem?

Think I may just have to go the DB::raw route for this one.

Axeia started a new conversation ->sync With Additional Values - Can't Wrap My Brain Around It

Hello,

I have a table like this

        Schema::create('trainer_shiny', function (Blueprint $table) {
            $table->string('trainer_name', 255);
            $table->string('pokemon_images_file_name', 255);
            //For pokémon that have a gender but without any visual difference.
            $table->tinyInteger('gender')->comment('1 = male, 2 = female, 3 = genderless'); 
            
            $table->primary(['trainer_name', 'pokemon_images_file_name', 'gender'], 'pk_trainer_shiny');
                
            $table->foreign('trainer_name')
                ->references('name')
                ->on('trainers')
                ->onDelete('CASCADE');
            $table->foreign('pokemon_images_file_name')
                ->references('file_name')
                ->on('pokemon_images')
                ->onDelete('CASCADE');
        })

And I want to insert values using the sync method on the trainer (e.g. $trainer->shinyPokemons()->sync($values); ) But I'm not quite getting how to insert the values.

        $trainer->shinyPokemons()->sync(['pokemon_icon_001_00_shiny.png' => [
            'gender' => [1, 2]
        ]]);```
Is getting me:
Error: "Array to string conversion (SQL: insert into `trainer_shiny` (`gender`, `pokemon_images_file_name`, `trainer_name`) values (1, pokemon_icon_001_00_shiny.png, Axxeia)) ◀"

    $trainer->shinyPokemons()->sync(['pokemon_icon_001_00_shiny.png' => [
        ['gender' => 1], 
        ['gender' => 2]
    ]]);
is getting me:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `trainer_shiny` (`pokemon_images_file_name`, `trainer_name`, `0`, `1`) values (pokemon_icon_001_00_shiny.png, Axxeia, 1, 2)) ◀"

Am I misunderstanding and does it only work for columns that aren't part of the primary key like my gender field is? Is there any way to make it work?
27 Oct
1 month ago

Axeia left a reply on Firefox And Laracasts.com/discuss

@Cronix

I made a tamper monkey script out of your code, you can find the script here: https://greasyfork.org/en/scripts/373670-laravel-firefox-forum-fix and tampermonkey here: https://tampermonkey.net/

So for all of us firefox users, install tampermonkey and then install the script and you're set until the redesign hits.

Axeia left a reply on Firefox And Laracasts.com/discuss

@Cronix you're welcome, wouldn't it make more sense to turn it into a tampermonkey script though?

Saves you the effort of clicking a bookmark(let) :)

26 Oct
1 month ago

Axeia left a reply on Firefox And Laracasts.com/discuss

@Snapey yes I did and tbh a scrollbar or linewrap is the expected behaviour in my opinion.

This is what happens in Firefox at the moment: image with the layout breaking

@shez1983 Are you sure the post disappears? What seems to happens is that the scrollbar is hidden and the textfield isn't big enough so it only displays the first few lines - however if you type something the textfield expands to fit the size of everything in it and you can see/edit your whole post. So I'm guessing there's some kinda of javascript watching for a content change and then calculating the needed size - I'm also guessing this bit of javascript should be called onFocus and that Chrome does do this (but Firefox does not).

Axeia left a reply on Firefox And Laracasts.com/discuss

Will do, thank you @9705996 :).

Axeia started a new conversation Firefox And Laracasts.com/discuss

Hello,

Thought I'd inform you that the forums are not working properly in Firefox. Long code fields with a long line in them break the layout.

Such as this one Such as this one  Such as this one Such as this one  Such as this one  Such as this one  Such as this one  Such as this one Such as this one ``` and then the forum-sidebar overlaps the forum post. 

Also when edditing a post and focussing the field where I type this very message in it doesn't expand to the needed size onFocus, I have to type something for it to scale up to the right size.

Axeia started a new conversation View Not Getting Removed In Down Function

Hello,

When running php artisan migrate:fresh --seed I get the error that the view already exists.


   Illuminate\Database\QueryException  : SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'eggfriends_count' already exists (SQL: CREATE VIEW eggfriends_count AS
           SELECT trainers.name, count(*) as eggfriends_count                                                                                                                                                                                                                 
             FROM eggfriends                                                                                                                                                                                                                                                  
             JOIN trainers ON accepter = name OR requester = name                                                                                                                                                                                                             
            WHERE accepted = true                                                                                                                                                                                                                                             
         GROUP BY trainers.name                                                                                                                                                                                                                                               
        )                                                                                                                                                                                                                                                                     

  at /home/Server/web/eggfriends/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'eggfriends_count' already exists")
      /home/Server/web/eggfriends/vendor/laravel/framework/src/Illuminate/Database/Connection.php:507

  2   PDO::exec("CREATE VIEW eggfriends_count AS
           SELECT trainers.name, count(*) as eggfriends_count
             FROM eggfriends
             JOIN trainers ON accepter = name OR requester = name
            WHERE accepted = true
         GROUP BY trainers.name
        ")
      /home/Server/web/eggfriends/vendor/laravel/framework/src/Illuminate/Database/Connection.php:507

  Please use the argument -v to see more details.```

I don't understand why however as the down function of this class is as follows:
```    public function down()
    {
        DB::unprepared('DROP TRIGGER insert_trainer');
        DB::unprepared('DROP TRIGGER delete_trainer');
        DB::unprepared('DROP VIEW eggfriends_count');
    }``` 

14 Oct
2 months ago

Axeia left a reply on Prevent Laravel From Inserting Parenthesis Around Union Queries?

In another place where another complex query was used that is what I ended up doing. The one above with some refinements as it didn't quite do what I wanted it to do yet*, is now fully 'eloquently' written.

  • Null values can be confusing to work with, also I was expecting boolean fields to return booleans but I just noticed they were tinyint(1) and === (as expected) didn't like that :p

I think you're on the money though, forcing complex queries to be rewritten to eloquents syntax will often be a waste time.

Axeia left a reply on Prevent Laravel From Inserting Parenthesis Around Union Queries?

Digging around some more this seems to be a known bug that got closed. I ended up rewriting a large part of the query to use whereNotIn and multiple where clauses instead.

Axeia started a new conversation Prevent Laravel From Inserting Parenthesis Around Union Queries?

Hello,

I'm using laravel 5.7.5 and running into a problem with my query which seemingly is due to Laravel inserting parenthesis around my unions. My code is as follows:

                $users = User::select(\DB::raw('
                users.name AS username, 
                trainers.name AS trainername,
                slug AS trainernameslug,
                TRUNCATE(latitude, 0) AS latitude, 
                TRUNCATE(longitude, 0) AS longitude, 
                share_location,
                eggfriends_count,
                eggfriend_cap,
                team,
                ROUND(( 6371 * acos(cos(radians('.$latitude.')) * cos(radians(ROUND(latitude, 2))) 
                * cos( radians(ROUND(longitude,2)) - radians('.$longitude.')) + sin(radians('.$latitude.')) 
                * sin( radians(ROUND(latitude,2))))), 2) AS distance'))
                ->join('trainers', 'users.id', '=', 'trainers.user_id')
                ->join('eggfriends_count', 'trainers.name', '=', 'eggfriends_count.name')
                ->whereNotIn('trainers.name', function($qReachedCap){
                    $dbPendingOrFriends = \DB::table('eggfriends')
                    ->select('accepter AS name')
                    ->where('requester', Auth::user()->active_trainer) // ?
                    ->where('accepted', '!=', \DB::raw(0)); // ? if it's null or true.

                    $dbOwnAccounts = \DB::table('trainers')
                    ->select('trainers.name')
                    ->where('user_id', \DB::raw(Auth::user()->id)); // = ?
                    
                    $qReachedCap->select('eggfriends_count.name')
                    ->from('eggfriends_count')
                    ->join('trainers', 'trainers.name', '=', 'eggfriends_count.name')
                    ->where('eggfriends_count', '>=', \DB::raw('eggfriend_cap'))
                    ->union($dbPendingOrFriends)
                    ->union($dbOwnAccounts);
                })
                ->orderBy('distance', 'DESC')
                //->toSql();
                //dd(str_replace("\n", ' ', $users));
                ->paginate(10);

Which results in the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'union (select `accepter` as `name` from `eggfriends` where `requester` = ? and `' at line 1 (SQL: select count(*) as aggregate from `users` inner join `trainers` on `users`.`id` = `trainers`.`user_id` inner join `eggfriends_count` on `trainers`.`name` = `eggfriends_count`.`name` where `trainers`.`name` not in ((select `eggfriends_count`.`name` from `eggfriends_count` inner join `trainers` on `trainers`.`name` = `eggfriends_count`.`name` where `eggfriends_count` >= eggfriend_cap) union (select `accepter` as `name` from `eggfriends` where `requester` = JBomb2411 and `accepted` != 0) union (select `trainers`.`name` from `trainers` where `user_id` = 1)))

commenting out the the paginate and uncommenting the toSql / dd I get the following query:

SELECT users.name AS username,
       trainers.name AS trainername,
       slug AS trainernameslug,
       TRUNCATE(latitude, 0) AS latitude,
       TRUNCATE(longitude, 0) AS longitude,
       share_location,
       eggfriends_count,
       eggfriend_cap,
       team,
       ROUND((6371 * acos(cos(radians(53.45595)) * cos(radians(ROUND(latitude, 2))) * cos(radians(ROUND(longitude, 2)) - radians(-2.15939)) + sin(radians(53.45595)) * sin(radians(ROUND(latitude, 2))))), 2) AS distance
FROM `users`
INNER JOIN `trainers` ON `users`.`id` = `trainers`.`user_id`
INNER JOIN `eggfriends_count` ON `trainers`.`name` = `eggfriends_count`.`name`
WHERE `trainers`.`name` NOT IN (
                                  (SELECT `eggfriends_count`.`name`
                                   FROM `eggfriends_count`
                                   INNER JOIN `trainers` ON `trainers`.`name` = `eggfriends_count`.`name`
                                   WHERE `eggfriends_count` >= eggfriend_cap)
                                UNION
                                  (SELECT `accepter` AS `name`
                                   FROM `eggfriends`
                                   WHERE `requester` = ?
                                     AND `accepted` != 0)
                                UNION
                                  (SELECT `trainers`.`name`
                                   FROM `trainers`
                                   WHERE `user_id` = 1))
ORDER BY `distance` DESC

Replacing the questionmark after requester = ? with a proper value phpmyadmin spits out the following error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UNION (SELECT accepter AS name ' at line 19. Removing all the parenthesis around the selects inside the NOT IN resolves the problem and the query completes. So my question is how do I keep laravel from inserting parenthesis around union queries?

14 Sep
3 months ago

Axeia left a reply on Validating A Request Using 'exists' Leading To SQL Error

ahhh Thank you, completely overlooked that :)

Axeia left a reply on Validating A Request Using 'exists' Leading To SQL Error

According to the documentation you link to it's exists:table,column. The table I'm trying to validate on is trainers and the column is name. My code is exists:trainers,name so unless I'm overlooking something I provide the required table to search in?

Axeia started a new conversation Validating A Request Using 'exists' Leading To SQL Error

Hello,

My validation is as follows:

            'name' => 'required|exists:trainers,name',
            'id' => 'required',
            'id.*' => 'numeric|exists:'
        ]);```
and my $_POST looks like this:
```Array ( [_token] => 0I6lF7rLocDwy0rgargtZ48fAiSjHuaLpfmyAfSj [name] => Axxeia [id] => Array ( [0] => 27 [1] => 69 [2] => 107 ) ) ```

When posting my form I get this error:
```SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where `id`.`0` = ?' at line 1 (SQL: select count(*) as aggregate where `id`.`0` = 27)```

Which makes sense as I expected the query to be:
```select count(*) as aggregate from `trainers` where `name` = 'Axxeia'```

The documentation states that the format is `exists:table,column` 

![table design showing the table and column do exists](https://puu.sh/BuT7r/fde12c033e.png "PHPMyAdmin trainers table")
29 May
2 years ago

Axeia left a reply on Using URL With A Slash In Its Value?

I used the [{https://github.com/cviebrock/eloquent-sluggable} eloquent-sluggable] package and that made it relatively easy to update my models/database. Just a bit of extra work to do in the views to set the references rights and update the controllers to findBySlugOrFail instead of findOrFail and I should be all set.

28 May
2 years ago

Axeia left a reply on Using URL With A Slash In Its Value?

Not the answer I was hoping to hear but I guess it's the right one, duplicating data to make more 'unique' data kinda rubs me the wrong way but it makes sense.

Axeia started a new conversation Using URL With A Slash In Its Value?

Hello, As my site is starting to shape up more and more and more data is input I've ran into a problem. I'm using the name of an item in my database as part of the URL as it's the primary key, however this name may contain a slash which throws laravel off-track as it treats it as an URL-separator. It's quite confusing to explain so I'll show some code instead. In my view I do the following: <th><a href="{{ url('/plushies', $plushy->name ) }}" title="added by {{ $plushy->addedBy }}">{{ $plushy->name }}</a></th> The $plushy->name contains a slash, in this case the value is 'Matsuri/Festival Alpacasso'. Is it possible to circumvent this somehow by being creative with the routing for example? At the moment my route is simply Route::resource('plushies', 'PlushiesController'); If not, what's the simplest way to prevent the issue altogether by replacing the / with for example '%2F' or even '|' ? Perhaps a setter can be defined on the request class to achieve this?

11 May
2 years ago

Axeia left a reply on Query With Constraints And Eager Loading With Constraints Mixed Together?

@pmall The array key on the 7th line should be 'Sizes' rather then 'Size' and there should be a ; character after the function on line #5, but otherwise perfect answer :) thank you!

Axeia started a new conversation Query With Constraints And Eager Loading With Constraints Mixed Together?

Hello, I've a query which will need constraints on some data that's eagerly loaded. I've tried to achieve this with the following code:

        $pYears = explode('-', $searchQuery->input('year'));
        $pSizes = explode('-', $searchQuery->input('size'));

        $plushiesQ = Plushy::with('Colors', 'Photos')
            ->with(['Sizes' => function($query) use(&$pSizes){
                $query->whereBetween('Sizes.size', $pSizes);
            }])
            ->whereBetween('yearOfRelease', $pYears);
        echo $plushiesQ->toSql();
        $plushies = $plushiesQ->get()->toArray();

The year constraint gets applied successfully but the size constraint gets ignored. Is the only way to make this work by writing the join manually as most examples on the internet seem to do? The echo reflects that the size constraint gets ignored as well, it outputs select * from "Plushies" where "yearOfRelease" between ? and ?

10 May
2 years ago

Axeia left a reply on How To Use Search Parameters In The Old Fashioned Format (search?name=value)

@Prez adding it to the route file does show the string instead of redirecting anywhere. Commenting it out and restoring Route::get('search', 'HomeController@search'); and then refreshing the page ends up in a redirect to the index ('/') again.

Axeia left a reply on How To Use Search Parameters In The Old Fashioned Format (search?name=value)

@Prez thanks for replying. Applying what you suggest (removing the {searchQuery} from the route) I get redirected to the index which quite what I had in mind. I don't think any of my routes is to blame for this, since it's still a limited number I'll just paste them here although I'm fairly sure the redirect is originating from some default Laravel behaviour?

//Home page.
Route::get('/', 'HomeController@index');

// Static routes for static pages
Route::get('about', 'StaticPageController@about');
Route::get('bootleg', 'StaticPageController@bootleg');

Route::get('json/title', 'JsonController@getTitle');

//Registration routes 
Route::get('register',  'Auth\AuthController@getRegister');
Route::post('register', 'Auth\AuthController@postRegister');

//Authentication routes (all but logout can't be accessed by guests)
Route::get('login',     'Auth\AuthController@getLogin');
Route::post('login',    'Auth\AuthController@postLogin');
Route::get('logout',    'Auth\AuthController@getLogout');

//Authenticated and admin-only routes
Route::resource('plushies', 'PlushiesController');
Route::resource('sizes',    'SizesController');
Route::resource('colors',   'ColorsController');
Route::resource('photos',   'PhotosController');
//Enables the create page to pre-select a plushy. Useful for adding a photo right after adding a plushy.
Route::get('/photos/create/{plushy_name}',   'PhotosController@create');
//For testing, this will remove all photos and thumbnails @TODO Remove me.
Route::get('photos/devOnly',   'PhotosController@devOnly');

//Performs a search for linkable/bookmarkable results. End-users should be able to filter down using javascript.
Route::get('search', 'HomeController@search');

Axeia started a new conversation How To Use Search Parameters In The Old Fashioned Format (search?name=value)

Hello, How do I get laravel to use an url in this format? search?name=akb&year=2011-2016&size=8-100? What I did so far is create this route: Route::get('/search/{searchQuery}', 'HomeController@search');

And my HomeController has the following method:

    {
        return 'Search route works!';
    }```
The SearchRequest class is nothing special atm, just extending the base request and overwriting the rules method with
```    public function rules()
    {
        return [
            'name'   => 'max:155',
            'year'   => ['regex:/^20[0-9]{2}:20[0-9]{2}$/'], //2000:2099
            'sizes'  => ['regex:/^[0-9]{1,3}:[0-9]{1,3}$/'], // 0-999:0-999
            'colors' => '',
        ];
    }```

If I visit MySite/search?name=akb&year=2011-2016&size=8-100 I get a error
```NotFoundHttpException in RouteCollection.php line 161:```

Preferably it would only accept urls with the questionmark?key=value markup as well instead of /key/value. And to make things possibly more complicated, the 'colors' source you can see in the validation rules is a ```<select multiple>``` so if no values are selected it won't be part of the url. 
12 Apr
2 years ago

Axeia started a new conversation Using Entrust To Restrict Access By Role, Throwing A HttpException

Hello,

I'm using the (Zizaco/Entrust)[https://github.com/Zizaco/entrust] package with laravel and it's "almost" working as expected. In my views I can do things like this fine

            @if(@Auth::check())
             <span class="navbar-right">
                 Welcome                  
                 @role('admin')
                 <span class='glyphicon glyphicon-education'></span> 
                 @endif
                 {{ Auth::user()->username }} <a href='/logout' id='login'><span class='glyphicon glyphicon-log-out '></span></a></span> 
            @else
            <a href='/login' id='login' class='navbar-right'><span class='glyphicon glyphicon-log-in '></span></a>
            @endif

and it works as expected. I only get to see glyph-span if I'm logged in and if the account I'm using has the admin role. However having done the following in the constructor my controller.

        $this->middleware('auth');
        $this->middleware('role:admin');

Leads to a very long error dump like below if the user doesn't have an admin role. If the user does have the admin role the page is rendered as expected.



HttpException in Application.php line 905:


1. in Application.php line 905
2.at Application->abort('403', '', array()) in helpers.php line 30
3.at abort('403') in EntrustRole.php line 39
4.at EntrustRole->handle(object(Request), object(Closure), 'admin')
5.at call_user_func_array(array(object(EntrustRole), 'handle'), array(object(Request), object(Closure), 'admin')) in Pipeline.php line 124
6.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
7.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
8.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 28
9.at Authenticate->handle(object(Request), object(Closure))
10.at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
11.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
12.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
13.at Pipeline->Illuminate\Routing\{closure}(object(Request))
14.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
15.at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
16.at ControllerDispatcher->callWithinStack(object(PlushiesController), object(Route), object(Request), 'index') in ControllerDispatcher.php line 54
17.at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\PlushiesController', 'index') in Route.php line 174
18.at Route->runController(object(Request)) in Route.php line 140
19.at Route->run(object(Request)) in Router.php line 724
20.at Router->Illuminate\Routing\{closure}(object(Request))
21.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
22.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64
23.at VerifyCsrfToken->handle(object(Request), object(Closure))
24.at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
25.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
26.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
27.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
28.at ShareErrorsFromSession->handle(object(Request), object(Closure))
29.at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
30.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
31.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
32.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 62
33.at StartSession->handle(object(Request), object(Closure))
34.at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
35.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
36.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
37.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
38.at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
39.at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
40.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
41.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
42.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
43.at EncryptCookies->handle(object(Request), object(Closure))
44.at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
45.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
46.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
47.at Pipeline->Illuminate\Routing\{closure}(object(Request))
48.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
49.at Pipeline->then(object(Closure)) in Router.php line 726
50.at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
51.at Router->dispatchToRoute(object(Request)) in Router.php line 675
52.at Router->dispatch(object(Request)) in Kernel.php line 246
53.at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
54.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
55.at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
56.at CheckForMaintenanceMode->handle(object(Request), object(Closure))
57.at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
58.at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
59.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
60.at Pipeline->Illuminate\Routing\{closure}(object(Request))
61.at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
62.at Pipeline->then(object(Closure)) in Kernel.php line 132
63.at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
64.at Kernel->handle(object(Request)) in index.php line 53

So the error seems to be in the handle method of the entrustrole class rather then my own code? The handle method is as follows

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  Closure $next
     * @param  $roles
     * @return mixed
     */
    public function handle($request, Closure $next, $roles)
    {
        if ($this->auth->guest() || !$request->user()->hasRole(explode('|', $roles))) {
            abort(403);
        }

        return $next($request);
    }

Trying to make that I'm looking for the problem in the right place and if this possibly a fault from the package that should be reported rather then me making a mistake. (I'm still very new to laravel)

11 Apr
2 years ago

Axeia left a reply on Registration Working, Authentication Not Work

It was indeed a POST request. I seem to have resolved the issue somehow while doing some work I could do in the meantime while I couldn't login. One of the changes I made to the User class or a form or validator must have fixed whatever it was that was going wrong.

Thanks for thinking along guys :) time to move on to the middleware lessons.

09 Apr
2 years ago

Axeia left a reply on Registration Working, Authentication Not Work

Thank you for responding :).

I've yet to reach the episode discussing middleware so I'm not sure if I fully understand you. My route.php file however is free of anything I didn't add myself.

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', 'HomeController@index');

// Static routes for static pages
Route::get('about', 'StaticPageController@about');
Route::get('bootleg', 'StaticPageController@bootleg');

//Registration routes
Route::get('auth/register',  'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

//Authentication routes
Route::get('auth/login',     'Auth\AuthController@getLogin');
Route::post('auth/login',    'Auth\AuthController@postLogin');
Route::get('auth/logout',    'Auth\AuthController@getLogout');*/


//All of the color REST routes, except delete?
Route::resource('colors', 'ColorsController');
Route::get('colors/{name}/delete', 'ColorsController@delete');

//All of the plushy REST routes, except delete?
Route::resource('plushies', 'PlushiesController');

Route::get('/home', 'HomeController@index');

If I run php artisan route:list I do get the following which contains quite a few more routes then I thought I had and the last column does have two different types of middleware for both App\Http\Controllers\Auth\AuthController and App\Http\Controllers\Auth\PasswordController.

+--------+--------------------------------+--------------------------------------------------------+------------------+------------------------------------------------------------+------------+
| Domain | Method                         | URI                                                    | Name             | Action                                                     | Middleware |
+--------+--------------------------------+--------------------------------------------------------+------------------+------------------------------------------------------------+------------+
|        | GET|HEAD                       | /                                                      |                  | App\Http\Controllers\HomeController@index                  | web        |
|        | GET|HEAD                       | about                                                  |                  | App\Http\Controllers\StaticPageController@about            | web        |
|        | GET|HEAD                       | auth/login/{one?}/{two?}/{three?}/{four?}/{five?}      |                  | App\Http\Controllers\Auth\AuthController@getLogin          | web,guest  |
|        | POST                           | auth/login/{one?}/{two?}/{three?}/{four?}/{five?}      |                  | App\Http\Controllers\Auth\AuthController@postLogin         | web,guest  |
|        | GET|HEAD                       | auth/logout/{one?}/{two?}/{three?}/{four?}/{five?}     |                  | App\Http\Controllers\Auth\AuthController@getLogout         | web,guest  |
|        | POST                           | auth/register/{one?}/{two?}/{three?}/{four?}/{five?}   |                  | App\Http\Controllers\Auth\AuthController@postRegister      | web,guest  |
|        | GET|HEAD                       | auth/register/{one?}/{two?}/{three?}/{four?}/{five?}   |                  | App\Http\Controllers\Auth\AuthController@getRegister       | web,guest  |
|        | GET|HEAD|POST|PUT|PATCH|DELETE | auth/{_missing}                                        |                  | App\Http\Controllers\Auth\AuthController@missingMethod     | web,guest  |
|        | GET|HEAD                       | bootleg                                                |                  | App\Http\Controllers\StaticPageController@bootleg          | web        |
|        | POST                           | colors                                                 | colors.store     | App\Http\Controllers\ColorsController@store                | web        |
|        | GET|HEAD                       | colors                                                 | colors.index     | App\Http\Controllers\ColorsController@index                | web        |
|        | GET|HEAD                       | colors/create                                          | colors.create    | App\Http\Controllers\ColorsController@create               | web        |
|        | GET|HEAD                       | colors/{colors}                                        | colors.show      | App\Http\Controllers\ColorsController@show                 | web        |
|        | DELETE                         | colors/{colors}                                        | colors.destroy   | App\Http\Controllers\ColorsController@destroy              | web        |
|        | PUT|PATCH                      | colors/{colors}                                        | colors.update    | App\Http\Controllers\ColorsController@update               | web        |
|        | GET|HEAD                       | colors/{colors}/edit                                   | colors.edit      | App\Http\Controllers\ColorsController@edit                 | web        |
|        | GET|HEAD                       | colors/{name}/delete                                   |                  | App\Http\Controllers\ColorsController@delete               | web        |
|        | GET|HEAD                       | home                                                   |                  | App\Http\Controllers\HomeController@index                  | web        |
|        | GET|HEAD                       | password/broker/{one?}/{two?}/{three?}/{four?}/{five?} |                  | App\Http\Controllers\Auth\PasswordController@getBroker     | web,guest  |
|        | GET|HEAD                       | password/email/{one?}/{two?}/{three?}/{four?}/{five?}  |                  | App\Http\Controllers\Auth\PasswordController@getEmail      | web,guest  |
|        | POST                           | password/email/{one?}/{two?}/{three?}/{four?}/{five?}  |                  | App\Http\Controllers\Auth\PasswordController@postEmail     | web,guest  |
|        | GET|HEAD                       | password/reset/{one?}/{two?}/{three?}/{four?}/{five?}  |                  | App\Http\Controllers\Auth\PasswordController@getReset      | web,guest  |
|        | POST                           | password/reset/{one?}/{two?}/{three?}/{four?}/{five?}  |                  | App\Http\Controllers\Auth\PasswordController@postReset     | web,guest  |
|        | GET|HEAD|POST|PUT|PATCH|DELETE | password/{_missing}                                    |                  | App\Http\Controllers\Auth\PasswordController@missingMethod | web,guest  |
|        | POST                           | plushies                                               | plushies.store   | App\Http\Controllers\PlushiesController@store              | web        |
|        | GET|HEAD                       | plushies                                               | plushies.index   | App\Http\Controllers\PlushiesController@index              | web        |
|        | GET|HEAD                       | plushies/create                                        | plushies.create  | App\Http\Controllers\PlushiesController@create             | web        |
|        | DELETE                         | plushies/{plushies}                                    | plushies.destroy | App\Http\Controllers\PlushiesController@destroy            | web        |
|        | PUT|PATCH                      | plushies/{plushies}                                    | plushies.update  | App\Http\Controllers\PlushiesController@update             | web        |
|        | GET|HEAD                       | plushies/{plushies}                                    | plushies.show    | App\Http\Controllers\PlushiesController@show               | web        |
|        | GET|HEAD                       | plushies/{plushies}/edit                               | plushies.edit    | App\Http\Controllers\PlushiesController@edit               | web        |
+--------+--------------------------------+--------------------------------------------------------+------------------+------------------------------------------------------------+------------+

You're saying I should remove the web middleware, but it's not in my my own routes.php list so I'm not sure how to approach this.

Axeia started a new conversation Registration Working, Authentication Not Work

Hello, I'm new to laravel and I've been following the "Laravel 5 Fundementals" videos hoping to learn how to work with laravel. I made it to [url=https://laracasts.com/series/laravel-5-fundamentals/episodes/15?autoplay=true]episode 15[/url] but now I'm running into a problem. I can confirm that if I use /auth/registration I can sign up new users successfully however trying to sign in a user doesn't seem to work.

I've set the AuthController (App\Http\Controllers\Auth\AuthController) to redirect to my homepage (/) and set some custom validation rules.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{    
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectTo = '/';
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username'  => 'required|max:255|unique:users,username',
            'email'     => 'required|email|max:255|unique:users,email',
            'password'  => ['required', 'min:8', 'max:255', 'confirmed',
                'regex:~^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}|.{20,}$~'],
            'realName'  => 'max:255'
        ]);
    }
    protected function create(array $data)
    {
        return User::create([
            'username'  => $data['username'],
            'email'     => $data['email'],
            'password'  => bcrypt($data['password']),
            'realName'  => empty($data['realName']) ? null : $data['realName']
        ]);
    }
}

In my controller for the root domain (/) I've set it as following:

    public function index()
    { 
        if(\Auth::check())
            return \Auth::user();
        return view('home');
    }

And I always get the view instead of the user, var_dump'ing \Auth::user() gives me a null value. My app\Http\User.php is as follows:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public $primaryKey = 'userName';  
    public $incrementing = false;    
    public $redirectPath = '/auth/login';

    protected $fillable = ['username', 'email', 'realName','password']; // Allow mass assigning
    protected $hidden = [
        'password', 'remember_token',
    ];
}

And I have not modified any class it inherits from. Could someone please tell me how to further debug this, from what I've understood from the tutorial video if I get redirected I should have a successful login, otherwise I would have been redirected to the form itself. Doing a var_dump($errors) in my root view isn't giving me any insight either.

02 Apr
2 years ago

Axeia left a reply on Installing Composer/laravel For The First Time, Minimum-stability Issue

Thank you, I did indeed run that not too long after writing this post and that does run successfully :).

30 Mar
2 years ago

Axeia started a new conversation Installing Composer/laravel For The First Time, Minimum-stability Issue

Hello,

I'm new to both composer and laravel and I'm running into a problem with the very first step to getting started. I downloaded composer with: curl -sS https://getcomposer.org/installer | php then I tried to install laravel with the command /usr/bin/composer.phar global require "laravel/composer" But as I was getting this error: Could not find package laravel/composer at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability I googled around a little bit and ended up running /usr/bin/composer.phar diag which mentioned composer.json FAIL and Checking pubkeys: FAIL along with a You are not running the latest stable version run composer-self-update to update etc etc. So as asked to do I ran /usr/bin/composer.phar self-update which ran fine.

I ran the diag again and only got a fail on Checking composer.json everything else checked out fine this time. Then I ran /usr/bin/composer.phar global require "laravel/composer" once more but got the same stability error as I got previously. Can I fix this with a command or do I need to create a JSON file in the home .composer/ directory and what should be in there?

PS: I have no desire to run the virtual machine even though it would be a lot more starter friendly, my server machine is short on resources