TuffRivers

TuffRivers

Member Since 2 Years Ago

Experience Points
3,800
Total
Experience

1,200 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
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
3,800 XP
Apr
13
3 months ago
Activity icon

Started a new Conversation Question About Application "State"

I am trying to learn Vue, and want to get some concepts down. I read alot about vuex and state. Is my understanding of state accurate ?

"state" or "store" is used because we could have components that read/manipulate the same objects on the same page, and if they are ready/writing directly from those components and not a "state" or "store" components would have different data?

If component A and component B both have client name as a field, and i edit the client name in component A, if i am using state, it will automatically update the same client name in component B?

I also assume that is the point of "reactive" magic in vue.

Thanks!

Apr
07
4 months ago
Activity icon

Replied to Possible For Laravel Policy Without $arguments?

@bugsysha thank you for this it makes more sense. My only question is can i do this with a resource::route ? Or do i have to create the routes manually and apply the middleware to the index route thats specific for admins?

Thanks!!!

Activity icon

Replied to Possible For Laravel Policy Without $arguments?

@bugsysha im a bit confused are you able to show me an example? ive read through the docs, and i thought policy was for granular control over actions, which is what i thought i needed, eg admins can do all actions, users can only do show and update (where user->id = $model->id)

Activity icon

Started a new Conversation Possible For Laravel Policy Without $arguments?

I have a default policy that uses a constructor to inject the authenticated user. That means for some controllers, i have no arguments to pass the $this->authorize('action', $arguments);

for example

    public function index() //nothing here
    {
        
        $this->authorize('index'); //only admins can get ALL (returns for all clients) 

        return $this->sendResponse(Card::All());

    }

DefaultPolicy

 
public function __construct(){
        
     $this->user = Auth::user();  //get current auth user
        
    }
    
    public function index()
    {
        return $this->user->role == 'admin'; //if admin return true
    }

The issue is, if i dont pass any arguments, it fails at $this->authorize('action'); and wont go to the policy at all.

I can pass an empty variable but that seems hack, is there a better way?

Apr
06
4 months ago
Activity icon

Started a new Conversation Events -> Listeners Vs Handler

I am created an event, UserCreated, which will fire a welcome email. Ive seen a few different tutorials, some say create and event and a listener, then the listener will trigger an email. But ont he laravel 7x documentation, it says to use event and a event handler?

Which is better for my use cause? I just want a simple way to que the job so my user can create an account and close our the connection while the send email can run in the background.

Previously ive done this with a dispatch and a job, just not sure what is the best for this use case or the differences between these three methods.

Thanks

Apr
05
4 months ago
Activity icon

Started a new Conversation Can I Add A Laravel Policy To My Route?

Currently i have a default policy that applies to a majority of my models, and i have the authorize within each controller action like sho

    public function index()
    {
 
        $this->authorize('index');

        return $this->sendResponse($this->card->getAllCards());

    }

Is there a cleaner way to add my $this->authorize at a higher level? Maybe in route middleware? Also i feel like grabbing the action dynamically from the route would drastically reduce the amount of code id have to write, i would just have to find a way to inject the resource to test the condition in my authorize code

for example if i have post /cards get /cards/1 get /cards

if route = get /resource
$action = 'index' 
$this->authorize($action, $resource)

if route get /resource/1
$action = 'show'
$this->authorize($action, $resource)

Thanks

Activity icon

Started a new Conversation Are Wildcard Policies Possible In Laravel?

I want Clients and Admins to use the same controllers. Clients can only edit update delete controller actions where user->client_id = $model->client_id, and admins can edit/see/delete all.

I have tested a policy for one of my resources and it works. But I soon realized, 10/12 controllers require the exact same policy ruies. Can i create a wild card policy that would operate like this? How can i pass a "variable" model into the policy checks though? Is Model $model actually something that works or is that just pseudo code lol.

protected $policies = [
    Model1::class => WildcardPolicy::class,
    Model2::class => WildcardPolicy::class,
    Model3::class => WildcardPolicy::class,
];

WildcardPolicy::class

<?php

namespace App\Policies;




use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Auth;

class WildcardPolicy
{
    use HandlesAuthorization;

 
    public function __construct()
    {
        $this->user = Auth::user();
       
    }
 
    public function index(User $user)
    {
        return $this->user->role === 'admin';
    }
 								   Could be Card $card, Client $client, etc
    public function update(User $user, Model $model) //i have many models, how can i pass in model dynamically?
    {
        return $this->user->client_id === $model->client_id;
    }

Activity icon

Replied to Route Model Binding With Resource Routes?

snapey this works when i put Card $card in the controller fuction, but when i put it in the construct of the controller it returns a blank model

protected $card;
    

    public function __construct(Card $card){

        $this->card = $card;
      

    }

Show

   public function show()
    {     

  print_r($this->card);
}

Blank model, any idea?

Activity icon

Replied to Route Model Binding With Resource Routes?

I have multiple i just removed them from the code i posted here :P

Activity icon

Started a new Conversation Route Model Binding With Resource Routes?

How can i inject the model data into my routes with Route::resource routes? Is it automatically available because the resource creates /route/{id} ? I tried type hinting in my controller but that doesnt seem to work, it returns an empty model.

My Route

Route::group(['middleware' => 'jwt.auth'], function() {

    Route::resources([
    
        'cards' => 'api\Card\CardController'

        ]);
});

My controller

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Card $id)
    {     

	//how to access? everything i try returns blank
	// print_r($id)         
       
   
    }
Mar
28
4 months ago
Activity icon

Started a new Conversation Best Folder Structure For Code Reuse In Multi User Laravel App

I have clients and admin users in my laravel App web service API, using JWT to authenticate.

They share probably 90 percent of all functions in the application, the differences are clients have route model binding so they can only see their information. Admins have a few other special features that they can do.

I want to avoid as much code duplication as possible. Right now i have all of my CRUD functions outside my controllers nicely. Is my only option to duplicate my controllers into Admin and Client folders, but they can then use the same CRUD files, obviously the controllers will have different functions (for example clients wont have a DELETE function in any of there controllers).

Is this the best way to approach this? Like i said just trying to reduce amount of code duplication as i have quite a few controllers!

Thanks

Activity icon

Started a new Conversation JWT/Passport Auth For SPA - What Is Best For My Use Case?

Ive been doing a lot of research on SPA auth with laravel, from my understanding refresh tokens are NOT to be used with single page apps. Also note, i will be building the FE, not a third part access, and i will have a mobile app (refresh tokens best practice for mobile app).

From what i gather, i have two options to secure my API for my SPA specifically:

  1. Grant Code with PKCE (https://laravel.com/docs/7.x/passport#code-grant-pkce)
  2. JWT without refresh token example doc (https://www.codechief.org/article/laravel-6-rest-api-with-jwt-authentication-with-crud)

Option 1 seems like a bit more overhead on the client side to setup and requires passport which is a bit more baggage for what i need right now, but setting up the refresh token route for my mobile app is super easy /oauth/token

Option 2 seems easy and light weight, can setup refresh token as well for mobile app (might be abit more work), is it really less secure to have token that expires say every 24hrs?

Your input is appreciated.

Mar
27
4 months ago
Activity icon

Replied to Auth::user Returning Generic User?

Hmm ok ive tried that now but i get this error

Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\User given

new auth.php

    'providers' => [
        // 'users' => [
        //     'driver' => 'eloquent',
        //     'model' => App\User::class,
        // ],

        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
            // 'table' => 'users',
        ],
    ],

new model to add eloquent

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

Activity icon

Replied to Auth::user Returning Generic User?

@bobbybouwmann

I figured as such. What if im trying to not use eloquent (i want to get dirtier, i know eloquen is very useful and for 95 percent of what im doing its fine but i just want to do away with some of the magic before i use eloquent).

Would i have to manually build my user model in my controller, eg

$user = new User();
$user->id = //data from database userID
etc

Then actually call the create token method from that user object?

Thanks and sorry for rambling.

Activity icon

Started a new Conversation Auth::user Returning Generic User?

For some reason my Auth::user is returning a generic user object, and not my user model which has my traits to createToken and i cant seem to figure out why?

Error Call to undefined method Illuminate\Auth\GenericUser::createToken()", \ my generic class obviously does not inherit the trait for HasApiToken

auth.php

    'providers' => [
        // 'users' => [
        //     'driver' => 'eloquent',
        //     'model' => App\User::class,
        // ],

        'users' => [
            'driver' => 'database',
            'model' => App\Models\User::class,
            'table' => 'users',
        ],
    ],

App\Models\User

<?PHP

namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable  

{

    use HasApiTokens, Notifiable;

 /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name','last_name', 'email', 'password','alerts','status','client_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     
    public $id;
    public $first_name;
    public $last_name;
    public $email;
    public $alerts;
    public $status;
    public $client_id;
    public $password;

}

and my auth controller

use App\Models\User;

public function login($credentials)
    {
         

            if(Auth::attempt($credentials)){

                 $user = Auth::user(); //returns generic user object with my table from database with no traits for createtoken, error 

		$user = new User; //returns an empty user object but a real model, and returns a token

                $token =  $user->createToken('token')->accessToken; 

            return $token;

        }
        
        else {
 
            $error = [

                'error' => 'Invalid Email or Password.'
                
            ];
            
            return $error;
        }
Mar
24
4 months ago
Activity icon

Replied to Scopes With Laravel Passport

@sti3bas im having abit of trouble fully undestanding the documentation (sorry im a first timer), are you able to eloborate in regards to my question? Maybe scopes ARENT what im looking for ?

Thanks

Activity icon

Replied to Scopes With Laravel Passport

@sti3bas thanks!

Hmm i guess im still a bit confused.

So i just sent a new token request to oauth/token with the ADMIn scope. yes it turned up in my scopes column. But i guess i need the backend to inject the scope based on the user ($scope = select scope from user where email = email) or else anyone can send any scope on login and get access.

Do i need to create my own logic for this and not use the oauth/token end point? Or can i piggy back off the existing Passport code?

Thanks

Activity icon

Replied to Scopes With Laravel Passport

Apparently i cant read documentation:

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class, 'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

will actually check the id in the oath_access_tokens table, and if the scope is applied to that token, it will let them in :)

let me know if im understanding correctly!

Thanks

Activity icon

Started a new Conversation Scopes With Laravel Passport

I have a web API that i want to setup scopes for but im lost on one part, how will EVERY request check to ensure hte scope is being enforced and not changed in the front end? Does the middleware call the user from the database and check the scope, and if it matches with the request it will let it through? I am using oauth/token endpoint to receive the token and the refresh token.

For example these are my scopes:


        Passport::setDefaultScope([
            'client'
        ]);

        Passport::tokensCan([
            'admin' => 'All Permissions',
            'operator' => 'Submit Transactions, View Daily Information, Access Mobile Application',
            'client' => 'View Client',
        ]);

These are my routes (only admin so far)

Route::post('/login','API\Auth\[email protected]');

Route::middleware(['auth:api', 'scopes:admin'])->group( function () {

    Route::post('/user/register', 'API\User\[email protected]');

    Route::post('/user/delete', 'API\User\[email protected]');

    Route::get('/user/{id}', 'API\User\[email protected]');

    Route::get('/users', 'API\User\[email protected]');

});

Thanks

Mar
23
4 months ago
Activity icon

Started a new Conversation Code Review For My First End Point

Hi All,

I am building my first web service API (first party, i will build FE in angular). If you have time, please review my first endpoint which is create user. Purpose of this endpoint is to receive user details from a form, validate these details, insert into database, and send a welcome email. Currently everything works, i feel my controller is very clean, but i know i have A LOT to improve on.

Warnings: Im new to OOP (i built lots of adhoc PHP scripts for data sync and api stuff, nothing production quality) im trying not to use Eloquent (more of a learning project so i want to get dirty)

Concerns:

  1. Where am i not using an object that it would be best i could? I am not using my model at all (app\models\user), is this a bad thing? Where should i be initiating it and using ? This is my biggest concern.

  2. I feel like there is a much better way to pass data between my controller and my SendEmail/WelcomeEmail task but i just cant figure out the best way, this is just the way that worked.

  3. Is the repository pattern over kill, am i even using it correctly?

UserController.php

class UserController extends BaseController
{
    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function store(UserStoreRequest $request, UserRepository $userRepo)
    {     
       
         $validated = $request->validated();

         $userId = $userRepo->insert($validated);

         $userDetails = $userRepo->find($userId);
        
         SendEmail::dispatch($userDetails);

         return $this->sendResponse($userDetails, 'User created.');
    }


}

UserStoreRequest.php //form validation

class UserStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; //no auth currently set up
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
    'first_name' => 'string|required',
    'last_name' => 'string|required',
    'client_id' => 'nullable',
    'email' => 'unique:users,email|required|email',
    'password' => 'required',
    'c_password' => 'required|same:password',
        ];
    }

}

UserRepositoryInterface.php

interface UserRepositoryInterface
{

    public function insert($data);
    public function find($id);

}

UserRepository.php

class UserRepository implements UserRepositoryInterface
{
    /**
     * Create New User
     */
    public function store($validated)
    {
       
        $insertData['client_id'] = $validated['client_id'];
        $insertData['first_name'] = $validated['first_name'];
        $insertData['last_name'] = $validated['last_name'];
        $insertData['created_at'] = now();  
        $insertData['updated_at'] = now();
        $insertData['email'] = $validated['email'];
        $insertData['password'] =  bcrypt($validated['password']);

        $id = DB::table('users')->insertGetId($insertData); 
  
        return $id;
       
    }

     /**
     * Find User by ID
     */
    public function find($id)
    {

       $userDetails = DB::table('users')->select('id','first_name','last_name','client_id','email')->where('id', $id)->get();

        return $userDetails;

    }

}

SendMail.php //job to send email

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $userDetails;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userDetails)
    {    
        
        $this->userDetails = $userDetails; 
       
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        
        $email = new SendWelcomeEmail($this->userDetails);
        Mail::to($this->userDetails[0]->email)->send($email);

    }
}

SendWelcomeEmail.php //pass details to view so i can build dynamic welcome email (name, etc)

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendWelcomeEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $userDetails;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($userDetails)
    {

	$this->userDetails = $userDetails;
         
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.welcome');
    }
}

I really appreciate anyone who takes the time to comb through this and offer their insights as well as criticisms.

Thank you.

Mar
21
4 months ago
Activity icon

Replied to Query Builder And Models

@jlrdw

So i elected to use the repository pattern and i am able to insert my data by turning it into an array. I now want to get that user information as an object and send that object back to my controller so i can trigger an event (send welcome email).

Would i just search for the user based on the email, or is this a hack way of doing it?

<?php

namespace App\Repositories;
use Illuminate\Support\Facades\DB;
use App\RepositoryInterface\UserRepositoryInterface;
use App\Models\User;

class UserRepository implements UserRepositoryInterface
{



 
    /**
     * Create new public function
     */
    public function insert($request)
    {

        $newUser = array(
            "client_id" => $request->client_id,
            "first_name" => $request->first_name,
            "last_name" => $request->last_name,
            "email" => $request->email,
            "password" => bcrypt($request->password),
            "created_at" => now(),
            "updated_at" => now()
        );
         
        DB::table('users')->insert($newUser); 
  	// $userData = select from users where email = newUser['email'] ?
	//create user object
// $userObj = new User;
//$userObj->first_name = $user['first_name'].. etc
        // return user;
       
    }
}

Thanks

Activity icon

Replied to Query Builder And Models

@jlrdw

Thanks i guess i was just confused because im used to only working with arrays and never objects and now that im trying OOP i was confused that i would convert my data to array before inserting into database.

Activity icon

Replied to Query Builder And Models

@snapey, thanks i will give it a read for sure!!!

Activity icon

Replied to Query Builder And Models

care to share an example and how your set it up? Like are you executing this in the controller or in the model (i assume you call the formrequest class from either of them)

Activity icon

Replied to Query Builder And Models

So you suggest i just skip reposotiry and put the insert code either in controller or directly in model?

Activity icon

Replied to Query Builder And Models

this makes sense, would my UserRepositoryInterface look like?

interface UserRepositoryInterface
{
    public function insert($attributes);
 
}
Activity icon

Replied to Query Builder And Models

This is my code doing the save within the controller and not calling the model function

<?php
   
namespace App\Http\Controllers\API;
   
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;

use Validator;
   
class UserController extends BaseController
{
    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'string|required',
            'last_name' => 'string|required',
            'client_id' => '',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }

    
        $user = new User;
        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->client_id = $request->client_id;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
      
        $user->save();
       
   
        return $this->sendResponse($user, 'User created.');
    }
}
Activity icon

Replied to Query Builder And Models

Thats what i thought. But this is what my $usre object looks like before in $user>save() - first_name isnt null ?

[id] => //AI in the database
[first_name] => Enza //not null
[last_name] => B //not null
[email] => [email protected] //not null
[alerts] => //null allowed - auto set in database to 1
[status] => //null allowed - auto set in databsae to 1
[client_id] => //null allowed
[password] => y$czzIoE81YoMsBZRQRzW1RekVRutruuN0LQ0Twe9USNd3ChX3Gyw.m //nn
Activity icon

Replied to Query Builder And Models

@snapey i unsertand the benefits of an ORM and i also know for my use case 95% of what i need CAN be satisfied by eloquent, but i want to take a rougher approach and do things a bit dirtier with SQL (i actually really like working with SQL haha) and less abastraction

also $user->save() returns this error:

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2020-03-21 19:28:27, 2020-03-21 19:28:27)) in file 

my object:

App\Models\User Object
(
[fillable:protected] => Array
(
[0] => client_id
[1] => first_name
[2] => last_name
[3] => email
[4] => password
)

[id] =>
[first_name] => Enza
[last_name] => B 
[email] => [email protected]
[alerts] =>
[status] =>
[client_id] =>
[password] => y$czzIoE81YoMsBZRQRzW1RekVRutruuN0LQ0Twe9USNd3ChX3Gyw.m
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)

[withCount:protected] => Array
(
)

[perPage:protected] => 15
[exists] =>
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
)

[original:protected] => Array
(
)

[changes:protected] => Array
(
)

[casts:protected] => Array
(
)

[classCastCache:protected] => Array
(
)

[dates:protected] => Array
(
)

[dateFormat:protected] =>
[appends:protected] => Array
(
)

[dispatchesEvents:protected] => Array
(
)

[observables:protected] => Array
(
)

[relations:protected] => Array
(
)

[touches:protected] => Array
(
)

[timestamps] => 1
[hidden:protected] => Array
(
)

[visible:protected] => Array
(
)

[guarded:protected] => Array
(
[0] => *
)

[rememberTokenName:protected] => remember_token
[accessToken:protected] =>
)

I want to move all databse stuff outside of my controller as well from what tutorials ive seen this is the best practice?

Activity icon

Started a new Conversation Query Builder And Models

Hi All,

I am electing not ot use eloquent for this project and im new to OOP so im having a hard time understanding when i should be working with an object and when with arrays.

I am testing my web api service to create a new user but having some difficulty saving to my database. I know that if i use PDO i can create an insert statement and write my Request $request fields to an array and easily bind it and insert it in my model function insert($userOptions), but why would i then create a new model in my controller just to convert it to an array after? Can i write objects to my databse without eloquent?

Sorry for the confusion, im a noob!

Model

<?PHP

namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable

{

    use HasApiTokens, Notifiable;

    public $id;
    public $first_name;
    public $last_name;
    public $email;
    public $alerts;
    public $status;
    public $client_id;
    public $password;

    public function insert($user){

       DB::table('users')->insert($user); //this will not work because $user is an object
        return $user;
    }

}

Controller

<?php
   
namespace App\Http\Controllers\API;
   
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Validator;
   
class UserController extends BaseController
{
    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'string|required',
            'last_name' => 'string|required',
            'client_id' => '',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }

    
        $data = $request->only('first_name','last_name','client_id','email','password');
        
        $user = new User; //create a user model, whats the point if i just build it as an array and pass to my insert function ?
        $user->first_name = $data['first_name'];
        $user->last_name = $data['last_name'];
        $user->client_id = $data['client_id'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
      

        $user->insert($user); //call insert function in my model passing the user 
       
   
        return $this->sendResponse($user, 'User created.');
    }
}
Activity icon

Replied to Noob Trying To Setup Laravel As API Service Getting Only 404!

Sorry, everything was COMPLETELY wrong, i was trying to reinvent the wheel lol i didnt solve the issue i started all over again :)

Mar
20
4 months ago
Activity icon

Started a new Conversation Laravel Web API Auth

Hi All, i was looking at some tutorials that use Passport for authentication when using laravel as a web API, i was curious, if i were to say use Angular or React as a front end would i still need to send the CSRF token to the front end and send it back with every call?

Mar
17
4 months ago
Activity icon

Replied to Laravel Without Eloquent

@jlrdw thanks, id love to see an example.

Activity icon

Replied to Laravel Without Eloquent

ohh sorry so you mean you have a models folders with your models (classes) but you dont extend to Model ? @jlrdw

Activity icon

Replied to Laravel Without Eloquent

In a model or you mean in a class? @jlrdw

Activity icon

Replied to Laravel Without Eloquent

Thanks!

I guess my next question is... can i still use objects but i just dont use models ? And i would write my raw sql queries inside my classes for example if i wanted to get a client id i would just make a function in my client class that executes raw db query to obtain id? @piljac1

Mar
16
4 months ago
Activity icon

Started a new Conversation Laravel Without Eloquent

Hi All,

I have a personal project im working on where i really want to build the database from scratch and work with raw sql (lots of complex queries and joins not a simple crud app), so i would not be using eloquent (maybe using the query builder but is it better than PDO? I have much exp with PDO).

I know there are many ways to structure a project, but i really have no idea where to start. Would anyone be able to supply a few examples ? Also note i come from a procedural background but i have some experience in OOP.

Thanks