silverxjohn

silverxjohn

Member Since 1 Year Ago

Experience Points 17,520
Experience
Level
Lessons Completed 61
Lessons
Completed
Best Reply Awards 17
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.

16 May
8 months ago

silverxjohn left a reply on Session Variables Missing After Fail Logging In.

@Borisu I've already fixed it, by using put not flash and I've make it as a after middleware. And I've put on the terminate method forgetting the session variable and at the first request so that it will clear the session variable when successful login and first load. Thanks!

silverxjohn started a new conversation Session Variables Missing After Fail Logging In.

So, I have this middleware called CheckOneUser it has this code.

public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response;
    }

    public function terminate($request, $response)
    {
        if (! \Auth::check())
            return;

        $user = \Auth::user();

        if (!$user->session_id) {
            $user->session_id = \Session::getId();
            $user->last_activity = Carbon::now();
            $user->save();
        }
        else {
            $last_session = \Session::getHandler()->read($user->session_id);

            if ($last_session) {
                \Auth::logout();
                \Session::getHandler()->destroy(\Session::getId());
                \Session::flash('session', 'Someone already logged in.');
                return redirect()->route('login', ['session' => 'Someone already logged in.']);
            }
        }
    }

I want to happen is that when the user happens to login then someone is already logged in. I will return a message to my view. My view has this line where I can check if it has session.

                        {{session()->has('session') ? session()->get('session') : 'sadsa'}}

And my web.php looks like this.

Route::group(['middleware' => ['checkoneuser']], function () {
    Route::post('login', 'Auth\[email protected]');

    Route::get('login', 'Auth\[email protected]')->name('login');
});

I registered that middleware to my Kernel. It is working as intended user can't logged in but I can't seem to pass that session variable so that I can send it to my view.

21 Dec
1 year ago

silverxjohn left a reply on Passing Data Form V-for Loop To Modal Component

@rassem can you explain your situation more precisely? If it is okay for you, you can create a new thread with the details of your question then reply me the link here.

Thanks

17 Dec
1 year ago

silverxjohn left a reply on Image Upload Doesn't Work | Laravel 5.5

did you add an enctype attribute to your form?

<form action="/some/url" method="post" enctype="multipart/form-data">
15 Dec
1 year ago

silverxjohn left a reply on Customize Laravel Login Throttling 5.4

@r0bertinski That's neat! Thank you for letting us know :)

silverxjohn left a reply on Customize Laravel Login Throttling 5.4

@devlim maybe you've set the cache container as cookie instead of file (or redis)

If you instruct the cache to use cookie as its container, the user could just simply delete that cookie and can try again without respecting your throttle settings.

Also, if you reload your browser using ctrl + f5, it will clear your cookie contents which will reset the throttle.

Your safest bet is to use file for caching in the .env

silverxjohn left a reply on Fetch User Data When You Have User ID

Can you post your database structure?

The error tells us that your users table doesn't have a column named authors_id

Can you confirm that these tables and column do exists and that there's no typo?

silverxjohn left a reply on MethodNotAllowedHTTPException On API REST DELETE Request

Mayve try to re-cache the routes by running:

php artisan route:cache

silverxjohn left a reply on Ciphers Error

Try to re-generate a new key

php artisan key:generate

Then clear the caches

composer dump-autoload - o

And

php artisan config:cache

silverxjohn left a reply on Fetch User Data When You Have User ID

I think it should be get() instead of all()

$authors = Authors::with('user')->get();

silverxjohn left a reply on How Do You Convert This To Eloquent

@sargbah84 Sorry 'bout that. I missed one thing.

You see, the $jobs is a collection of a collection that' s why you are not able to access the property directly after the loop. To fix this, we need to flatten the Collection

$jobs = $user->stores->map(function ($store) {
    return $store->jobs;
})->flatten(1);

The integer 1 that we passed in the flatten()is the depth.

For more information, check the documentation (here) [https://laravel.com/docs/5.5/collections#method-flatten]

14 Dec
1 year ago

silverxjohn left a reply on How Do You Convert This To Eloquent

You can try usingCollection

$jobs = $user->stores->map(function ($store) {
    return $store->jobs;
});

$jobs should now have all the jobs the user currently has.

04 Sep
1 year ago

silverxjohn left a reply on Modify API Response Format Based On Querystring?

If you're doing it for only one route, you can live with what you've got. (e.g return response()->json(['data'=>$myRecords]);)

But if you're doing it on other controllers, I would suggest you to create a middleware instead

php artisan make:middleware DataWrapper
<?php

namespace App\Http\Middleware;

use Closure;

class DataWrapper
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($request->input('wrapper') == 'data')
                // return wrapped data

        return $response;
    }
}
23 Aug
1 year ago

silverxjohn left a reply on What Am I Gonna Do To Restrict Users From Inserting An Unapproved Request Into A Table?

Given your table structures, my approach would be

Create a Job or just any class that will hold the logic when changing the state (pending, approved, etc). So whenever I want to approve an animal, I don't need to remember to delete the item from pending and add the the animal to the approved table.

For example, in my console:

php artisan make:job AddAnimalToPendingJob

AddAnimalToPendingJob.php

class AddAnimalToPendingJob
{
    private $animal;

    public function __construct(Animal $animal, User $requestor)
    {
        $this->animal = $animal;
    }

    public function handle() {
        Pending::create([
            'animal_id' => $animal->id,
            'requestor_id' => $requestor->id
        ])->save();
    }
}

ApproveAnimalRequestJob.php

class ApproveAnimalRequestJob
{
    private $animal;

    public function __construct(Animal $animal)
    {
        $this->animal = $animal;
    }

    public function handle() {
        // remove the animal from your pending list
        Pending::where('animal_id', $this->animal->id)->delete();

        Approved::create([
            'animal_id' => $this->animal->id
        ])->save();
    }
}

DenyAnimalRequestJob.php

class DenyAnimalRequestJob
{
    private $animal;

    public function __construct(Animal $animal)
    {
        $this->animal = $animal;
    }

    public function handle() {
        // get the requestor id before deleting the data
        $user = Pending::where('animal_id', $this->animal->id)->first()->requestor;

        // remove the animal from your pending list
        Pending::where('animal_id', $this->animal->id)->delete();

        Notify::user($user, new AnimalRequestDeniedMail($this->animal));
    }
}
class MyController
{
    public function userSendRequest(Request $request)
    {
        // ...
        $this->dispatch(new AddAnimalToPending($animal));
    }

    public function adminApprovedTheRequest(Request $request)
    {
        // ...
        $this->dispatch(new ApproveAnimalRequestJob($animal))
    }

    public function denyTheRequest(Request $request)
    {
        // ...
        $this->dispatch(new DenyAnimalRequestJob($animal));
    }
}
17 Aug
1 year ago

silverxjohn left a reply on Request' Input Parameter Is Empty

After long hours of thoroughly searching the web, I found out that uploading a file on a PUT request is currently not allowed.

For reference, here's the link to the issue

(Input from PUT requests sent as multipart/form-data is unavailable)[https://github.com/laravel/framework/issues/13457]

16 Aug
1 year ago

silverxjohn left a reply on Request' Input Parameter Is Empty

@Snapey it's just 4kb.

I don't think it's the problem with the server since on my Create form, I can upload any files without a problem. I also configured my php.ini to accept up to 50MB post file.

Also, even if I remove the attachment from the form, the Input::all() is still empty.

silverxjohn started a new conversation Request' Input Parameter Is Empty

I'm trying to send a request from my front-end to Laravel. But Laravel doesn't seem to catch it.

Here's my code from client (JS)

return new Promise((resolve, reject) => {
    let formData = new FormData();

    formData.append('attachment', data.attachment);
    formData.append('title', data.title);
    formData.append('content', data.content);
    formData.append('publish_on', data.publish_on);


    axios.put('some/url/1', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(response => {
        resolve(response);
    }).catch(error => {
        reject(error);
    });
});

For testing, I just dump the input from web.php

Route::put('some/url/{something}', function (Request $request) {
    dd(\Input::all());  // returns an empty array
    dd($request->input('title')); // returns a null
});

I'm sure the data has been pass to the server because when I click the Network tab on Chrome Developer Tools, I see it in my Request Payload.

The payload contains:

------WebKitFormBoundaryWmkUAKZRhAmLrvit
Content-Disposition: form-data; name="attachment"; filename="Sample.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


------WebKitFormBoundaryWmkUAKZRhAmLrvit
Content-Disposition: form-data; name="title"

The Title
------WebKitFormBoundaryWmkUAKZRhAmLrvit
Content-Disposition: form-data; name="content"

The Content
------WebKitFormBoundaryWmkUAKZRhAmLrvit
Content-Disposition: form-data; name="publish_on"

12-30-2016
------WebKitFormBoundaryWmkUAKZRhAmLrvit--

I need to use FormData here because I'm sending a file. This only happens when updating the resource. The creation is working fine.

PS: I'm using ES2016 syntax

30 Jul
1 year ago

silverxjohn left a reply on CSS Frameworks

No you don't need to delete anything. Everything is ready for you. Just run npm install

29 Jun
1 year ago

silverxjohn left a reply on Quick Question Regarding Separation Of Concerns

Is there an advantage to using facades rather than injecting dependencies, or is that just preference?

A preference. Both are testable.

For me, OOP isn't just about putting things in different classes. It's more of organization of code. I like to read books that talks about code organization (e.g Refactoring, Clean Code, etc.) and different techniques to write code (e.g Design Pattern, Data Structures, Algorithms, etc) because it's the topic that excites me most (next to learning new Language/Framework). They're fascinating. That's maybe the reason why I'm a bit too picky when reviewing code. I'm not saying I'm better than you or anyone. Reading != Experience.

The problem is that your code breaks most of SOLID

S for Single Responsibility.

You admitted it, your code breaks this rule.

You should at least have a class for Thread, ThreadReply/Post, Category, etc.

O for Open-closed principle

What if you add a functionality to Like a Post? User Achievements? you will have to modify so many methods. The fact that you've failed to achieve 'S' in SOLID means this 'O', too, failed.

L for Liskov Substitute

Components should be interchangeable. I can't think of an example. But it's about writing a parent class and using that parent class to type hint.

I for Interface segregation

I have no access to your code repository. Are you using interfaces? Something like this way (Probably a reference to Repository Pattern)

class Thread
{
    public function save(IThreadCreator $creator)
    {
        ..
        $creator->create(['title' => 'Some Title', 'content' => 'Some content']);
        ..
    }
}

D for Dependency inversion

You pass this LOL :)

What I'm trying to say is that you don't need to follow these conventions at all. Though it's really satisfying to conform into these standards, They're not always the best. Sometimes it's always better to do the job in a simple way. No lulu lala. But if you're trying to learn these principles, I think you should read more first. Not necessarily a book, just some blogs and articles you'll find.

SOLID The First 5 Principle of OOP From STUPID to SOLID code

Cheers!

28 Jun
1 year ago

silverxjohn left a reply on Quick Question Regarding Separation Of Concerns

@inet Actually, procedural isn't that bad. Your code isn't that bad. Yes you could put these methods up in a class but that would probably dirty your code base as it will need to maintain such many classes that only has a few methods. The only thing I'm concern of is your coding standard. You seem to like extra white space ;) It's your preference, that I understand but if you wish to contribute to the community, there's a standard that's been reviewed by many geeks and maestro. See psr-X standard. It simply just says no extra space before the parenthesis when defining a method:

public function myMethod($firstParameter, $secondParameter) { .. }

// as oppose to

public function myMethod ( $firstParameter, $secondParameter ) { ... }

I also thought Eloquent was doing so many magic tricks before. But I really like the syntax of it. So I dug in to the source code until I demystify the tricks.

Controller

Dependencies

Remove the Request and Auth in your Controller. You can use their Facade counterpart.

class ForumsController extends BaseController
{
    ...
    public function __construct (Forums $forums) { ... }
    ...
}

..

// So instead of using:
$this->auth->user();

// you can use:
Auth::user();

will will yield the same value.

Request

Request shouldn't be a class state. So instead of this:

public function postThread ( $thread )
    {
        return $this->forums->processReply(Auth::user(), (int)$thread, $thread, trim($request->input('text')));
    }

it could be rewritten:

public function postThread (Request $request, $thread )
    {
        return $this->forums->processReply(\Auth::user(), (int)$thread, $thread, trim($request->input('text')));
    }

Laravel will do its job and 'inject' the Request class with the input to your method. You'll only do this for every controller method that needs the Request

Validation

The only validation I find in your code is in processThread() and that you're using it in different method in your controller. I think this is fine other than recreating the validation for every methods in your controller. If you wish to create your custom class, you can. But know that there's nothing wrong with procedural.

27 Jun
1 year ago

silverxjohn left a reply on Quick Question Regarding Separation Of Concerns

If I do not want to use Laravel's validation service, should I still create my own separate validation class and put that logic there?

@inet Why don't you wanna use Laravel Validator? If you want, yes. But some people like to put the validation in a controller method. Your choice.

Also, your pseudo code calls, in the Request class, the following But, if I'm reading the documentation correctly, this would just return an integer (the topic ID). Should I call the forums model from the request class to then grab the actual object?

Yes.

It intrigues me. Why don't you want to use Laravel's validation or Eloquent? I mean what's the use of using Laravel as a framework if you don't use most of its functionality?

Also, your pingCheck() can be moved to a middleware.

These are just my suggestions. It is you who will decide which would fit best.

26 Jun
1 year ago

silverxjohn left a reply on Quick Question Regarding Separation Of Concerns

  1. Should the validation that is happening (i.e. does the topic exist, do you have permission to access the topic, and form validation) belong in this method, another method, or the controller? Another class?

Another class. Make use of Laravel's Request.

run php artisan make:request StoreThreadRequest

and define your validation rules. Then in your controller

class ThreadController
{
    ...
    public function postCreate(StoreThreadRequest $request)
    {
        // put your code here. You can now be sure that this method
        // will only be called when the validation pass.
        // if it fails, Laravel will do its job and return a proper response for you.
    }
    ...
}
  1. Should processThread() be grabbing the topic (the category the thread is being posted in) itself, or should the Controller grab that from the forums model and then pass that along as an argument?

Let's try to refactor your code. Remember we can move our validation rules in a custom Request class. So we remove validation in your code

public function processThread ( $user, $topic, $title, $text ) 
{
    // Grab topic user is attempting to post thread in
    $topic = $this->grabTopic($topic, ['id', 'access']);

    $id = DB::table('forumsThreads')->insertGetId([
        'topic'       => $topic->id,
        'user'        => $user->id,
        'title'       => $title,
        'text'        => $text,
        'time'        => time(),
        'latestReply' => time()
    ]);

    $this->ping($text, $user->username, '/forums/thread/'.$id);

    return redirect('/forums/thread/'.$id);

    Session::flash('errors', $errors);
    Request::flash();
    return redirect('/forums/create/'.$topic->id);

}

My next concern is the Redirect and Session. I believe they should be in Controller. Do note that we're now only return a boolean.

public function processThread ( $user, $topic, $title, $text ) 
{

    // Grab topic user is attempting to post thread in
    $topic = $this->grabTopic($topic, ['id', 'access']);

    $id = DB::table('forumsThreads')->insertGetId([
        'topic'       => $topic->id,
        'user'        => $user->id,
        'title'       => $title,
        'text'        => $text,
        'time'        => time(),
        'latestReply' => time()
    ]);

    $this->ping($text, $user->username, '/forums/thread/'.$id);

    return true;
}

Next is the Request.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreThreadRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $topic = $this->route()->getParameter('topic');

        // Check if topic exists/user has access to it
        return !$topic OR \Auth::user()->userlevel < $topic->access
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:60|min:3',
            'text' => 'required|max:255|min:10'
        ];
    }
}

Finally, in your controller

public function postCreate (StoreThreadRequest $request, $topic )
    {

        $auth    = $this->auth;

        $isThreadProcessed = $this->forums->processThread($auth->user(), (int)$topic, trim($request->input('title')), trim($request->input('text')));

        // remember the `processThread()` returns a boolean that tells us if the thread has been process.
        if ($isThreadProcessed)
            return redirect('/forums/thread/'.$id);
    }

If you're using Laravel 5.4, you can remove the trim() as there's a middleware that sanitizes string coming from a request. If you're in < 5.4, you can stick with it.

25 Jun
1 year ago

silverxjohn left a reply on App/Http/routes.php, Where It Is?

It has been moved to your-project-root-directory/routes/web.php

silverxjohn left a reply on I Need A Little Help In Making A UML Class Diagram.

Do I also need to have the Views in the diagram?

Views are out of scope when designing your UML diagram.

associate the base controller and base model?

It really depends whether you type-hint the model to your controller. e.g

class MyController extends Controller
{
    public function __construct(Model $model) { /*...*/ } 
}

The tircky part is if you're using the Facade

User::find(1);
22 Jun
1 year ago

silverxjohn left a reply on How To Insert A Video.mp4 In Database?

@otkrivashkin exactly right.

Then when you want to display/play the video:

<video src="{{ $video->thumbnail }}" ></video>

silverxjohn left a reply on Npm Run Dev Gives An Error

The folder @mdecooman asks you to delete is the folder in your project

your-project
 - app
 - config
 - database
 - node_modules <- this
 - test

Not the folder located in your Program Files

Re-install npm and npm-cli, delete the node_modules IN YOUR PROJECT then run npm run dev

08 Jun
1 year ago

silverxjohn left a reply on [HOW] Parent To Component: One Way Binding

@bunnypro Thanks. That did the work.

I'm just curious, is there any workaround for this? I hate to do this on all of my components.

07 Jun
1 year ago

silverxjohn left a reply on Pagination On Array

@firestruck, You could implement a paginator yourself with Laravel's LengthAwarePagination.

Here's the signature of its constructor:

public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])

We are interested in the first four arguments. So when we instantiate a new instance of LengthAwarePagination, we need to pass these parameters:

// whatever is the result of your query that you wish to paginate.
$items = [];

// The total number of items. If the `$items` has all the data, you can do something like this:
$total = count($items);

// How many items do you want to display.
$perPage = 5;

// The index page.
$currentPage = 1;

$paginator = new Illuminate\Pagination\LengthAwarePaginator($items, $total, $perPage, $currentPage)

If you're requesting the data from ajax, you can return it from your controller

return Response::json($paginator);

If you want to display the buttons for pagination to your Blade:

<div class="row">
    {{ $paginator->links() }}
</div>

silverxjohn started a new conversation Parent To Component: One Way Binding

On my example here: https://jsfiddle.net/silverxjohn/w1s775cu/1/

I don't want the data from the main Vue instance updates whenever I edit the component properties.

  • Click the button Edit User From a component
  • Write something on any fields.
  • Close the modal. The data you typed has been reflected on the parent's data.

What I want is that when I pass the data to a component via its props, I want to give it a new copy and not a shared instance so when I change the copy, the other doesn't changes.

24 May
1 year ago

silverxjohn left a reply on MethodNotAllowedHttpException In RouteCollection.php Line 251:

@ipula

Sorry for the late response,

The middleware auth:api adds a prefix to your route.

So if you have a route:

Route::get('users', '[email protected]');

You hit it by using this url: api/users. Make note of the api/ prefix

19 May
1 year ago

silverxjohn left a reply on MethodNotAllowedHttpException In RouteCollection.php Line 251:

Perhaps you're sending a different type.

In PostMan, make sure you're sending with POST and not GET

18 May
1 year ago

silverxjohn left a reply on Naming Controller Convention

@JordanMiguel That's not what I meant.

What I mean is that, adding a separate controller inside the Panel folder (namespace, if you will) is redundant.

I believe in the ration: 1 resource = 1 controller.

You can just add a new method in Controllers\NewsController

/*
 * Displaying news for admin
 *
 */
public function adminIndex()
{
    return view('admin.news.index');
}

/*
 * Displaying news for normal users
 *
 */
public function index()
{
    return view('admin.news.index');
}

Cheers!

silverxjohn left a reply on How To Insert The Fetch Multiple Rows Data To Another Table?

@achieve100 Honestly, I don't know what it is you're trying to accomplish.

Would you mind sending a link to your code repository and explain exactly it you're trying to do?

I'm sure many people here in this forum would like to help you. But do us a favor by explaining things so that it is easier for us to understand.

Communication is the key! lol

silverxjohn left a reply on Getting A List Of Users With A Specific Role While Using Entrust.

@finchy70 Are you sure you name the method scopeHasRole ?

silverxjohn left a reply on Naming Controller Convention

Since you're dealing solely with News, One controller is enough.

Controllers
-> NewsController

You should try creating controller with artisan:

php artisan make:controller NewsController --resource

The --resource flag will let Laravel to include methods that are primarily used on many cases.

Like storing news:

public function store(Request $request) { /* ... */ }

Updating news:

public function update(Request $request) { /* ... */ }

And to show the form where the user can update the news:

public function edit()
{
    return view('some.view');
}
17 May
1 year ago

silverxjohn left a reply on How To Insert The Fetch Multiple Rows Data To Another Table?

Make sure you add

protected $fillable = ['Date', 'Badge', 'CEN', 'PFN', 'LNAM', /* etc. */ ];

In your model

silverxjohn left a reply on Code Inside Event Listener Not Working

I think the culprit is in this method:

public function postRegister(Request $request)
{
    ...
        
    event(new UserRegistered(Auth::user()));

    return response()->json();
}

The user is suppose to be register and not login. So Auth::user()(I'll assume) will be null.

silverxjohn left a reply on Getting A List Of Users With A Specific Role While Using Entrust.

@finchy70

If you wish to use this syntax:

User::hasRole('user')->get();

In your User model class, add the following method:

class User
{
    /*  Code omitted */

    public function scopeHasRole($query, $role)
    {
        $query->where('role', '=', $role);
    }
}

You can use it like so:

public function create()
{
    $userList = User::hasRole('admin')->get();

    return view('templates.createadmin', compact('userList'));
}

silverxjohn left a reply on Accounts Are Auto-Activating Themselves?

Can you provide us the registration code?

I'm pretty sure it's defaulting activated attribute to true.

When you create a new user, you must explicitly write the default value.

User::create([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => '[email protected]',
    'activated' => false,
    /* code omitted */
]);

You can try XDebug with PHPStorm. It makes debugging easy.

silverxjohn left a reply on Updating A Users Role In User_role Table With Eloquent When Using Entrust.

You can override the attachRole() from entrust like so

<?php

use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent
{
    // We use EntrustUserTrait but change the `attachRole()` method name
    // to `entrustAttachRole()` so we can override the method but still
    // access the original (trait's) method
    use EntrustUserTrait {
        attachRole as protected entrustAttachRole;
    }

    /**
     * Alias to eloquent many-to-many relation's attach() method.
     *
     * @param mixed $role
     */
    public function attachRole($role)
    {
        // remove any roles tagged in this user.
        foreach ($this->roles as $userRole) {
            $this->roles()->detach($userRole->id);
        }

        // attach the new role using the `EntrustUserTrait` `attachRole()`
        $this->entrustAttachRole($role);
    }
}

The above code will keep your existing code working. But if you could refactor you can just simply create a new method:

<?php

use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent
{
    use EntrustUserTrait;

    public function deferAndAttachNewRole($role) {
        // remove any roles tagged in this user.
        foreach ($this->roles as $userRole) {
            $this->roles()->detach($userRole->id);
        }

        // attach the new role using the `EntrustUserTrait` `attachRole()`
        $this->attachRole($role);

    }
}
16 May
1 year ago

silverxjohn left a reply on Vue.JS - Material Components - Mix/Webpack

@ejdelmonico Could you explain more a bit why we should stay away from require()?

It is being used in the laravel repo:

https://github.com/laravel/laravel/blob/master/resources/assets/js/bootstrap.js

So I just used it everytime I add a package.

silverxjohn left a reply on Need To Append A Field From A Lookup Table In My Result Collection.

class Address extends Model
{
    public $fillable = ['state_id'];

    public $appends = ['state'];

    public function getStateAttribute()
    {
        return $this->state()->first();
    }

    public function state()
    {
        return $this->belongsTo('App\State');
    }
}

Resulting JSON will return:

{
    number: '443',
    street: 'some street',
    state: {
        name: 'New York',
        created_at: 'Some date',
        updated_at: 'Some date'
    },
    created_at: 'Some date',
    updated_at: 'Some date'
}

silverxjohn left a reply on Vue.JS - Material Components - Mix/Webpack

Did you require the package in your resources/assets/bootstrap.js?

You gotta do something like:

require('material')

silverxjohn left a reply on Passing Data Form V-for Loop To Modal Component

@junik91

You just need to import Bootstrap's css and js file in your <head>.

Then, for simplicity, just copy your modal template right after the <body> section of your html.

I personally make my master layout like this:

#master.blade.php

<html lang="en">
<head>
    <title>@yield('title')</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    @yield('modals')

    <div class="container">
        @yield('content')
    </div>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

And whenever I extend the master

@extends('layouts.master')

@section('title', 'My Page')

@section('modals')
<!-- here's a modal snippet copied from http://getbootstrap.com/javascript/ -->

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <h1>Hooray!</h1>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
@endsection

@section('content')
<h1>Welcome to my Page!</h1>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>
@endsection
15 May
1 year ago

silverxjohn left a reply on Populate Bootstrap Model With Table Data.

@tonydavis1995

In that case:

https://jsfiddle.net/m5hr7914/4/

I hope it helps. Let me know if you need further help.

silverxjohn left a reply on [Problem] JQuery Click Event With Represent Wrong Values From Eloquent

If you don't mind changing your implementation:

https://jsfiddle.net/m5hr7914/2/

I made this for someone else with the same problem as yours. If you need more help, let me know.

silverxjohn left a reply on How Do I Use Csrf_token In An External Javascript File

In your master layout page:

<html lang="en">
<head>
<title>@yield('title')</title>

<!-- Add this meta tag -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

<body>
    <!-- Code omitted -->
</body>

<script>
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>
</html>

This way, you don't need to worry about setting csrf code anywhere in your ajax.

Read more: https://laravel.com/docs/5.4/csrf

silverxjohn left a reply on [Problem] JQuery Click Event With Represent Wrong Values From Eloquent

In your master layout page:

<html lang="en">
<head>
<title>@yield('title')</title>

<!-- Add this meta tag -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

<body>
    <!-- Code omitted -->
</body>

<script>
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>
</html>

This way, you don't need to worry about setting csrf code anywhere in your ajax.

Read more: https://laravel.com/docs/5.4/csrf

silverxjohn left a reply on Getting TokenMismatchException In VerifyCsrfToken.php Line 68 Sometime

Try this:

{{ Form::open(array('id'=>'login_form','class'=> 'panel p-a-4')) }}
    {{ csrf_field() }}
            <label>
              <input type="email" name="email" placeholder="Email" />
            </label>
            <label>
              <input type="password" name="password" placeholder="Password" />
            </label>
            <label>
               Keep me logged in<input type="checkbox" checked />
            </label>
            <label>
              <button type="submit" id="signin_btn"><span>Login</span></button>
            </label>
{{ Form::close() }}