on3nx

on3nx

Member Since 2 Years Ago

Singapore

Experience Points 4,130
Experience Level 1

870 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 27
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

04 Aug
9 months ago

on3nx left a reply on Laravel 5 - Passing Variable To Relationship Model

Hi, Let me try to elaborate more.

So my user model receive additional data from outside (3rd party service not db) when it is called/initiated.

The data collected from 3rd party is all together with task data as well, so i keep it as protected variable inside user model to be pass to my task model later on.

To reduce request to 3rd party service, i would like to pass this protected variable to task model when task model initiated (i dont want task model to pull/request the data to user model as the data is a protected data)

So is there way to achieve this?

on3nx started a new conversation Laravel 5 - Passing Variable To Relationship Model

if i have below model:

class User extends Model{
    protected $someDataFromExt = ['taskID0' => 'test', 'taskID1' => 'ting'];
    public function tasks() { return $this->hasMany('Task'); }
}

class Task extends Model{
    protected $appends = ['ext_data'];
    public function user() { return $this->belongsTo('User'); }
    public function getExtDataAttribute(){ return $this->external_data; }
}

i would like, when i do: $tasks = auth()->user()->tasks->all(); i want to pass $user->someDataFromExt (based on task ID) to task model, so i later in my $tasks variable I can access:

foreach($tasks as $task){
    echo $task->ext_data;
}

which will return data that was given from user model earlier.

is this possible? how?

23 Jul
10 months ago

on3nx left a reply on How To Set Has Many Relation Cross Database

Thanks @lostdreamer_nl lemme try, but before that just wondering, how the Table1 model knows to look at DB that defined in DB_Name because I could have few DBs...

on3nx started a new conversation How To Set Has Many Relation Cross Database

I Have:

DB_A:Table_1  |            +--| DB_B:Table_User |
------------------+            |   +-----------------------+ 
DB_Name       +--->>--+  | User_ID                   |
------------------+                +-----------------------+

In DB_A Table_1 Field DB_NAME referencing to another DB

I would like to know how to setup eloquent relationship for model Table_1

class Table_1 extends Model{
    public function users(){
        return $this->hasMany( /* ?? */);
        /* what should i put here to tell that Table_1 has many users from DB that reference from DB_Name field?  */
    }
}
21 Jul
10 months ago

on3nx started a new conversation How To Check If The ID Belong To Authenticated User Before I Delete?

Hi,

this maybe noob question, but i'm wondering, is the delete method is actually being secured by Laravel at behind?

for example?

as normal CRUD with resource route:

you may have standard blade {!! Form::open([ 'method' => 'DELETE', 'route' => ['tasks.destroy', $task->id] ]) !!} {!! Form::submit('Delete this task?', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!}

and in Controller public function destroy($id){ $task = Task::findOrFail($id);

    $task->delete();

    Session::flash('flash_message', 'Task successfully deleted!');

    return redirect()->route('tasks.index');
}

so question, will it be secured if: the route ['tasks.destroy', $task->id] will point to some url like this: domain.com/task/5 I can change 5 to any number and submit post - will it protect automatically, so it only allow to delete 5 if task 5 belong to authenticated user? or i have to manually check and validate it?

if I have to validate it, can it be done using Validate function: $this->validate($request, [ 'id' => 'required|somehow|???', ]);

or I have to manually eloquent query?

20 Jul
10 months ago

on3nx started a new conversation Laravel 5.6 CSRF Token Not Validating / Checked

I have:

Blade

<form class="form-horizontal was-validated" method="POST" action="{{ route('account.applications.index')}}">
  {{ csrf_field() }}
  {{-- yadda yadda yadda --}}
  <div class="form-group row">
    <label class="col-sm-2 col-form-label">&nbsp;</label>
    <div class="col-sm-10">
      <input id="application_type" type="hidden" name="application_type" value="{{ Request::get('application') }}">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

received by controller:

public function store(Request $request)
{

    $requestData = $request->all();

    $requestData['application_id'] = strtolower(trim($requestData['application_id'].'.'.config('app.fqdn_base')));

    $request->replace($requestData);

    $values =  $this->validate($request, [
        'application_type' => 'required|exists:applications,name',
        /* other validations */
    ]);

    $exitCode = Artisan::call('tenant:create', [
        /* passing param here */
    ]);

    $host = Hostname::where('fqdn', $values["application_id"])->first();
    $web = $host->website;

    $web->name = $values["application_name"];
    $web->application_id = Application::where('name', '=', $values["application_type"])->pluck('id')->first();
    $web->owner = auth()->id();
    $web->save();

    $applications = Application::where('id', '!=', '0')->get();
    return view('admin.applications', [ "applications" =>  $applications]);
}

above code is working fine, except... CSRF function, I have check that I could retrieve CSRF value from request.

however, once my transaction done and redirect to the page that I want, If I press F5 it will re-submit the form, and this should result CSRF missmatch, but in my case, It didn't.

is there a specific way to turn on CSRF validation?

14 Nov
2 years ago

on3nx left a reply on Auth Facade Not Working After Changing User Model

@rsands,

Bear in mind, there is no table/database transparent to laravel or this web app.

It's all about response from rest server.

And to answer your question, no id The key is UserId which web app or laravel will only receive it from rest server (again, not database)

Thanks

on3nx left a reply on Where Is Static Auth::User Method Code Goes Into

Thank you @rsands,

Yes it should correct. I change that pKey to UserId

The idea is: when i req from rest server it will return bunch of user data and i will assign userModel->UserId to userid that i got from rest server.

Any implication on that?

on3nx left a reply on Where Is Static Auth::User Method Code Goes Into

hi @rsands,

thanks for the reply,

you can see my entire code here: https://github.com/on3nx/LaravelMultipleDB/blob/7edf7288f637a87f073d59066442057b5308357c/app/Models/RestUser.php

it's not a done code so it is quite messy there, however, register, login is work fine, it just to get the user data through Auth::user is not work,

very much appreciate for the kind help

Thanks

on3nx left a reply on Where Is Static Auth::User Method Code Goes Into

Thanks @martinbean,

i have my config/auth.php as follow:

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'rest',
        'model' => App\Models\MyUserModel::class,
    ],
],

'passwords' => [
    'users' => [
        'connection' => 'myConn',
        'provider' => 'users',
        'table' => 'user_tokens',
        'expire' => 60,
    ],
],

and MyUserModel class I build from scratch but referencing Eloquent user model.

the problem here is, Auth::User, Auth::user()->firstname., Auth::user()->lastname (and i guess the other methods as well) is not working properly.

it didn't throw any error, it's just nothing happend. i would like to trace, where is the part that is 'not connected' here...

Thanks!

13 Nov
2 years ago

on3nx started a new conversation Where Is Static User Method Code Goes Into

hi,

im trying to build my own user model.

i have a quick question, where is this static user method and load('profile') goes into?

Auth::user()->load('profile');

Thank you..

26 Oct
2 years ago

on3nx started a new conversation Type Error: Argument 1 Passed To Auth\SessionGuard::login() Must Implement Interface Auth\Authenticatable, Instance Of Http\RedirectResponse Given

hi,

I'm running Laravel 5.3 and try to modify my registration code to have activation mail feature as referenced in: https://blog.damirmiladinov.com/laravel/laravel-5.2-email-verification-with-activation-code.html#.WBCTI_l946Q

but i received error: FatalThrowableError in SessionGuard.php line 441: Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\Http\RedirectResponse given

here is my create method inRegisterController: protected function create(array $data){ $user = new RestUser($data); $user->register(); $this->activation->sendActivationMail($user); //return redirect('/login')->with('activationStatus', true); return redirect('/login')->with('status', 'We sent you an activation code. Check your email.'); //return $user; }

how can i overcome this?

thanks!

15 Oct
2 years ago

on3nx started a new conversation About Config/auth.php

10 Oct
2 years ago

on3nx started a new conversation Changing User Providers To Rest Driver

hi,

i have requirement to move user eloquent driver to REST driver - means: all of user relevant transaction will be done through REST API instead of database or eloquent driver.

so, my guess, i should start from config/auth.php and change:

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent', // <--- change this to my own REST driver
        'model' => App\Models\User::class, // <-- change this to my own custom model
    ],
],

where should i start to build my own custom driver and model to change it into REST?

thank you,

04 Oct
2 years ago

on3nx started a new conversation What Is Remember Token Column For?

quick question,

what is remember token column used for in users database?

is that for "remember me" or for "session"

how is that works?

thanks,

03 Oct
2 years ago

on3nx started a new conversation Change User DB With Rest API

Hi,

my question might be too wide here, but i'm looking for where should i start and what is the best way to achieve this.

here is the background:

i have a standard Laravel with User login, forgot pass, register, etc. using standard package that laravel provide. they are all works perfects.

but then, i have a requirements, to move any user related transaction (login, reset pass, register, etc.) to be managed by another system - which this system will provide an REST API for Laravel to call.

so, my Laravel will no longer interact with User DB anymore, instead of my REST API interface.

I'm thinking to use Guzzle for REST API transaction(please let me know if you think there are better option for this)

but the real question is this: where should i terminate the 'standard user transaction' process and replace it with rest api call instead of db call?

i believe, controller and route should remain the same...

Thank you, and let me know if the question is not clear :D

Cheers,

29 Sep
2 years ago

on3nx left a reply on Where Is Password_resets Table Defined?

@InaniELHoussain

lol

I will mark it as answer when the button works! :D

on3nx left a reply on Where Is Password_resets Table Defined?

@InaniELHoussain thanks for your help, it works, but i don't know why i can't mark your comment as answer...

27 Sep
2 years ago

on3nx left a reply on Where Is Password_resets Table Defined?

@InaniELHoussain thanks for your reply

Let me try and let you know

Thank you

on3nx started a new conversation Where Is Password_resets Table Defined?

Hi

for some reason, i have to change/move password_resets table to another database.table.

i would like to know, where is this table name defined, so i can change it to database.table name that i want.

Thanks!

on3nx left a reply on Data Disappear When I Do Model->save()

Hi @InaniELHoussain & @Jaytee ,

Thanks! it works now!

you guys are awesome!

:)

on3nx left a reply on Data Disappear When I Do Model->save()

@InaniELHoussain Thanks for reply,

I just tried that, it's not work, obviously User_ID won't be sent to database.

at Model->save(array(/*no user id here*/'token' => '525323523')) in Activation.php line 83

thanks

on3nx started a new conversation Data Disappear When I Do Model->save()

i did below in my model class: private function createToken($user){ $token = $this->getToken(); $this->save([ 'user_id' => $user->id, 'token' => $token ]); return $token; }

it's obvious that i put user id and token there to be inserted to my DB.

however, once i run the program, it throw me an error: Field 'user_id' doesn't have a default value

and i found out that my user_id and token disappear from the query, as you can see in the error stack below:

in Connection.php line 761
at Connection->runQueryCallback('insert into `user_tokens` (`updated_at`, `created_at`) values (?, ?)', array('2016-09-27 15:22:20', '2016-09-27 15:22:20'), object(Closure)) in Connection.php line 717
at Connection->run('insert into `user_tokens` (`updated_at`, `created_at`) values (?, ?)', array('2016-09-27 15:22:20', '2016-09-27 15:22:20'), object(Closure)) in Connection.php line 481
at Connection->statement('insert into `user_tokens` (`updated_at`, `created_at`) values (?, ?)', array('2016-09-27 15:22:20', '2016-09-27 15:22:20')) in Connection.php line 435
at Connection->insert('insert into `user_tokens` (`updated_at`, `created_at`) values (?, ?)', array('2016-09-27 15:22:20', '2016-09-27 15:22:20')) in Processor.php line 32
at Processor->processInsertGetId(object(Builder), 'insert into `user_tokens` (`updated_at`, `created_at`) values (?, ?)', array('2016-09-27 15:22:20', '2016-09-27 15:22:20'), 'id') in Builder.php line 2142
at Builder->insertGetId(array('2016-09-27 15:22:20', '2016-09-27 15:22:20'), 'id')
at call_user_func_array(array(object(Builder), 'insertGetId'), array(array('updated_at' => '2016-09-27 15:22:20', 'created_at' => '2016-09-27 15:22:20'), 'id')) in Builder.php line 1433
at Builder->__call('insertGetId', array(array('updated_at' => '2016-09-27 15:22:20', 'created_at' => '2016-09-27 15:22:20'), 'id')) in Model.php line 1607
at Model->insertAndSetId(object(Builder), array('updated_at' => '2016-09-27 15:22:20', 'created_at' => '2016-09-27 15:22:20')) in Model.php line 1576
at Model->performInsert(object(Builder)) in Model.php line 1472
at Model->save(array('user_id' => '2', 'token' => '219bcefd2c8d745f8f010216b18cd96d59d509b8a8af5ec07cecd1cd220e95b1')) in Activation.php line 83
at Activation->createToken(object(User)) in Activation.php line 59

Am I missed anything here?

Thank you

26 Sep
2 years ago

on3nx started a new conversation Set DB Connection In Class Illuminate\Database\Connection

I have below Class:

class SomeClass{
    protected $db;

    public function __construct(Connection $db){
        $this->db = $db; // <-- how to set this DB to 'another' DB connection, instead of default connection
    }

    private function accessDB($data){
        $this->db->table($this->table)->where('data', $data)->update([
        'update' => $update,
        'created_at' => new Carbon()
        ]);
        return $update;
    }

question: how do i configure my $this->db to use 'my secondary' or 'another' DB connection.

*assuming i have done setup my config/database.php to have 2 DB connections.

Thanks!

25 Sep
2 years ago

on3nx left a reply on Multiple Database

Hi @joexanderson , @brainlabs2010 ,

I just tried and it works!

thanks for the kind help.

here are the summary:

return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:another.users',
        'password' => 'required|min:6|confirmed',
    ]);

for some reason, you have to do this:

class User extends Authenticatable{
    use Notifiable;
    protected $connection = 'another';

because this:

    protected function create(array $data){
        return User::create([
            'connection' => 'core',
            //bla
        ]);
    }

didn't work... don't know why

Thanks Guys!

24 Sep
2 years ago

on3nx left a reply on Multiple Database

@brainlabs2010 , @joexanderson , and everyone

Thanks for the kind help, let me try and let you know the result tomorrow

Thanks!

23 Sep
2 years ago

on3nx left a reply on Multiple Database

@joexanderson and @jimmck ,

another finding that i found:

if i set:

'default' => 'web',

to

'default' => 'another',

that works - means, the registration process will take data from 'another' connection

but it's not what i want, default should be 'web' connection.

on3nx left a reply on Multiple Database

Hi @jimmck thanks for the reply,

what i'm trying to do is to separate 'User related' data with 'Web related' data for other purpose other than website.

my db connections are:

'default' => 'web', //you said "But the default database for the 2 connections are different", - the default is 'web'
'connections' => [
  'web' => [
    // bla
    'database' => 'db_host1',
    // bla
  ],
  'another' => [
    // bla
    'database' => 'db_host2',
    // bla
  ],
]

the error is: db_host1.users - sorry it was a typo, i will fix it.

i'm actually not even intend to touch db_host1 first. i'm just trying to use default auth method but only using db_host2 (another connection) instead of db_host1 (web connection)

i hope this clarify my question

Thanks,

on3nx left a reply on Multiple Database

Hi @joexanderson ,

i just uploaded the whole code, are you able to see this: https://github.com/on3nx/LaravelMultipleDB

Thanks!

on3nx left a reply on Multiple Database

@joexanderson Thanks for your help,

and yeah, still not working, here i made github: https://gist.github.com/anonymous/2519a90ecd9770f1ff8f4791162768f1

those are files that i modify, if you need other files, let me know

on3nx left a reply on Multiple Database

@joexanderson Thanks for the reply,

I did that in:

class User extends Authenticatable{
use Notifiable;
protected $connection = 'another';
// bla

and still, it's pointing to my 'web' DB connection.

on3nx started a new conversation Multiple Database

This maybe common question, but i've been stuck for 2 days T_T

it's pretty simple,

  1. I create a new laravel 5.3 project

  2. I remove db config in .env file

  3. i define 2 x db connection in config/database.php as follow: 'connections' => [ 'web' => [ 'driver' => 'mysql', 'host' => 'localhost', 'port' => '3306', 'database' => 'db_host1', 'username' => 'username1, 'password' => 'secret1', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'another' => [ 'driver' => 'mysql', 'host' => 'localhost', 'port' => '3306', 'database' => 'db_host2', 'username' => 'username2', 'password' => 'secret2', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ], it's clear and straight forward

  4. php artisan make auth

  5. modify migrations as follow: class CreateUsersTable extends Migration{ //bla.... public function up() { Schema::connection('another')->create('users', function (Blueprint $table) { //bla } //bla }

    class CreatePasswordResetsTable extends Migration{ //bla.... public function up() { Schema::connection('another')->create('password_resets', function (Blueprint $table) { //bla } //bla } it's clear and straight forward

  6. php artisan migrate - sweet, db created in a right place

  7. goto registercontroller.php and modify create method as follow: protected function create(array $data) { return User::create([ 'connection' => 'another', 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); }

  8. test to register user - fill up all form fields and submit

  9. DANG! error comeout: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'web.users' doesn't exist (SQL: select count(*) as aggregate from users where email = [email protected])

question: why it still look up from 'web' DB connection as i have told to use 'another' DB connection T_T ?

am i missed anything here?

i have read a couple doc like: http://fideloper.com/laravel-multiple-database-connections but it doesnt help me...

appreciate if someone could help me here :)

cheers,

22 Sep
2 years ago

on3nx left a reply on Change User Db To Different Db Connection

@kassim3 thank you for the reply,

yes, i have the db configured properly (means: it's in the correct db)

but, for any reason, when you try to login / register, Laravel is looking for my user data in my 'web' DB connection

which render me this error: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'web.users' doesn't exist (SQL: select count(*) as aggregate from users where username = on3nx)

so i need to tell in somewhere in the code that, user related, please use 'another' DB connection

on3nx started a new conversation Change User Db To Different Db Connection

I have config/database.php as follow:

'default' => 'web',

'connections' => array(

# Our primary database connection
'web' => array(
    'driver'    => 'mysql',
    'host'      => 'host1',
    'database'  => 'database1',
    'username'  => 'user1',
    'password'  => 'pass1'
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

# Our secondary database connection
'another' => array(
    'driver'    => 'mysql',
    'host'      => 'host2',
    'database'  => 'database2',
    'username'  => 'user2',
    'password'  => 'pass2'
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

),

and i'm using standard laravel 5.3 user authentication.

if i like to move or change the db connection for anything related with user (e.g. login, register, forgot pass, etc.), where is the settings that i need to change?

Thanks!

on3nx left a reply on How To Set-up Multiple Database Connection

@Ruffles no, in the future there will be a lot of connections, as in dynamically added connection

21 Sep
2 years ago

on3nx left a reply on How To Set-up Multiple Database Connection

Thanks @Ruffles thats explained the different.

*i was made a confusing title before :) which i had update it.

so , for my case, if i require multi db connection, how can i achieve this in configuration?

on3nx started a new conversation What The Different Db Config In .env And Database.php In Config Folder?

Hi,

i'm trying to make multiple db connection, i saw: http://fideloper.com/laravel-multiple-database-connections i set my db config in config/database.php as follow:

'default' => 'web',

'connections' => array(

    # Our primary database connection
    'web' => array(
        'driver'    => 'mysql',
        'host'      => 'host1',
        'database'  => 'database1',
        'username'  => 'user1',
        'password'  => 'pass1'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Our secondary database connection
    'another' => array(
        'driver'    => 'mysql',
        'host'      => 'host2',
        'database'  => 'database2',
        'username'  => 'user2',
        'password'  => 'pass2'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
),

i build my schema as well.

but then when i want to run artisan migrate it said:

[InvalidArgumentException] Database [mysql] not configured.

I understand that mysql is read from .env file (because if i change to something the name changed)

anyway, so if i like to setup multi db connection, which config should i do? seems like there is 2 db config to me..

thanks and appreciate the help!

on3nx left a reply on How To Load Assets Into Laravel 'properly'

Thanks @tomi and @nate.a.johnson

your link: https://laravel-news.com/2015/10/setup-bootstrap-sass-with-laravel-elixir/ helps a lot.

basically (correct me if i'm wrong),

  1. define your dependencies in package.json
  2. load them 'npm install'
  3. your assets will be loaded in: 'node_modules'
  4. define it in: 'resources/assets/sass/app.scss'
  5. then gulp it.

if you have multiple files, you can configure it using elixir which explained in: https://laravel.com/docs/5.3/elixir

Thanks!

on3nx started a new conversation How To Load Assets Into Laravel 'properly'

Hi,

i'm still learning how gulp, npm, elixir and laravel - how are they related.

I know that if you want to load asset into laravel, you can just copy paste the file into the folder and load it directly from your blade template.

but i'm wondering , if i have jquery, or bootstrap or any standard/common assets, how to load it 'properly' in laravel? - rather than i download and copy-paste the file and load it manually in blade template.

Thanks, 1-nk

18 Sep
2 years ago

on3nx left a reply on How To Update Data From Relational Table Database

thanks @Shovels i saw you do save twice:

$user->username = $request->username; ... $user->save();

// Now save the profile data
$user->profile->dateofbirth = $request->dob;

$user->profile->save();

is there any way to do it one shot?

anyway,

i found a solution (which i'm not sure if it's right)

as below:

$requestOnly = []; // validate input - ignore if it's empty string if($request->has('email')) { $requestOnly[] = 'email'; }

...

// then execute: $user->fill($request->only($requestOnly))->save();

with that, the only problem is on password i try did:

if($request->has('password')) { $request->input('password') = bcrypt($request->input('password')); $requestOnly[] = 'password'; $flashMessage[] = 'Password'; }

but not working...

on3nx started a new conversation How To Update Data From Relational Table Database

Hi

if i have data like:

Table user:

  • id
  • username
  • password
  • firstname
  • lastname

Table profile:

  • id
  • userid (foreign to table user - id)
  • dateofbirth
  • gender
  • etc.

i like to build 'update user profile page' i manage to make the eloquent relationship right, and i'm able to present the data correctly in update profile page as follow:

class ProfileController extends Controller {

protected $fillable = ['email', 'firstname', 'lastname', 'dob', 'gender', 'password'];

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{

    return Validator::make($data, [
        'email' => 'email|max:255|unique:users',
        'firstname' => 'alpha|max:255',
        'lastname' => 'alpha|max:255',
        'dob' => 'date|olderThan|max:255',
        'gender' => 'max:255',
        'password' => 'min:6|confirmed',
    ]);
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $user = Auth::user()->load('profile');
    return view('auth.profile', compact('user'));
}

/**
 * Update the user's profile.
 *
 * @param  Request  $request
 * @return Response
 */
public function update(Request $request)
{
    $anyChange = false;
    $flashMessage = [];

/*** how to update the data here? */ $user = Auth::user()->load('profile'); $user->email = $request->email; $user->firstname = $request->firstname; $user->lastname = $request->lastname; $user->dateofbirth = $request->dob;

    $user->save();

   flash()->success('testing 1234');

    return back();
}

}

the problem is: how can i update the user data. if i do like code above - it throw me error in sql query which it's actually trying to input the whole request input into 1 table. here is the error: "Column not found: 1054 Unknown column 'dateofbirth' in 'field list' (SQL: update users set email = , firstname = aaa, lastname = , updated_at = 2016-09-18 14:40:12, dateofbirth = where id = 9"

off course dateofbirth column not exist in table users,

do i have to input this manually? or laravel has a way to do this better?

thanks!

on3nx left a reply on Redirect To Previous Page After Login

@Laraveldeep I'm using 5.3 i'm sorry, but not really sure for your case, so far it works fine on me.

on3nx left a reply on Redirect To Previous Page After Login

Ok, i solve that with this: $this->redirectTo = URL::previous(); - in my login controller: i'm not sure if there any issue with my approach here:

class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */

use AuthenticatesUsers;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/home';

protected $loginPath = '/login';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->redirectTo = URL::previous();
    $this->middleware('guest', ['except' => 'logout']);
}

}

on3nx left a reply on Redirect To Previous Page After Login

@SaeedPrez I'm sorry i think i missed that.

ok, and yes i just realize if the page is not protected by the auth middleware, after login (i have login form in every page in header.blade) it will always redirect to /home.

so I assume i should create authenticated() method in my controller, am i right? - let me try this and see if it's works

thanks for your kind help!

on3nx left a reply on Redirect To Previous Page After Login

@SaeedPrez you right! thanks for the help, it's default laravel behavior. then i'm wondering, if i like to change this default behavior, how i do this? e.g. everytime i login go to /about page and when i suppose to use intended(); ?

on3nx left a reply on Redirect To Previous Page After Login

Thank you for the reply @SaeedPrez

Where should i put: return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($

In my case above?

on3nx started a new conversation Redirect To Previous Page After Login

This maybe a very basic question.

I have /privatepage that only authenticated user able to access

questions:

  1. how to redirect to /login, if i'm guest (not authenticated) and i hit /privatepage
  2. once i'm successfully login from /login, how to redirect to the previous page (/privatepage)
  3. similar like no.2 - in /login page, if i come from /aboutpage (which a public page) - after login successfull, how do i redirect back to /aboutpage (or the previous page)?

i read redirect()->intended() function but i'm still dont understand fully.

ok, let's put it this way,

if i have: privatepage controller:

class PrivateController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); }

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('private');
}

}

when i hit private page as guest, it will redirect me to login page but after i login, it will redirect me to home page (the page that come in standard laravel package)

how to redirect to privatepage after i login?

Thank you

16 Sep
2 years ago

on3nx left a reply on Laravel 5.3 - Routing As Auth::routes();

i just wondering, what is the purpose of this Auth::routes() ?

will it the same if i put:

// Authentication Routes... Route::get('login', 'Auth\[email protected]')->name('login'); Route::post('login', 'Auth\[email protected]'); Route::post('logout', 'Auth\[email protected]');

    // Registration Routes...
    Route::get('register', 'Auth\[email protected]');
    Route::post('register', 'Auth\[email protected]');

    // Password Reset Routes...
    Route::get('password/reset', 'Auth\[email protected]');
    Route::post('password/email', 'Auth\[email protected]');
    Route::get('password/reset/{token}', 'Auth\[email protected]');
    Route::post('password/reset', 'Auth\[email protected]');

in web.php?

while i saw: Route::get('/home', '[email protected]'); in web.php

so, should i do my route in auth.php or in web.php?