Ranx99

Experience

1,200

0 Best Reply Awards

  • Member Since 8 Months Ago
  • 1 Lesson Completed
  • 0 Favorites

21st July, 2018

Ranx99 left a reply on Vimeo For Business • 1 day ago

@garethdaine

I have the same question, what did you end up with using?

20th July, 2018

Ranx99 left a reply on Error While Trying To Update Multiple Has Many Relation! • 2 days ago

@staudenmeir

class Page extends Model
{
    public function sections()
    {
        return $this->hasMany('App\Models\Section');
    }
}

class Section extends Model
{
    public function page()
    {
        return $this->belongsTo('App\Models\Page');
    }
    
    public function requirements()
    {
        return $this->hasMany('App\Models\Requirement');
    }
}

class Requirement extends Model
{   
    public function section()
    {
        return  $this->belongsTo('App\Models\Section');
    }
}

19th July, 2018

Ranx99 left a reply on Error While Trying To Update Multiple Has Many Relation! • 3 days ago

I was also thinking maybe something like this would work, but it doesn't :( why is that ?

$page->with(['sections.requirements' => function ($query) {
            $query->whereIn('id', $ids_array)
            ->orderByRaw("FIELD(id, {$ids_string})")
            ->update([
               'sortOrder' => DB::raw('@rownum  := @rownum  + 1'),
            ]);
        }]);

18th July, 2018

Ranx99 started a new conversation Error While Trying To Update Multiple Has Many Relation! • 4 days ago

Iam trying to update 'sortOrder' column based on a given list of ids. For example, if the given IDs are:

$orderList = ['id' =>'1','id' =>'5','id' =>'3']
ID of '1' => 'sortOrder column'  = 1
ID of '5' => 'sortOrder column'  = 2
ID of '3' => 'sortOrder column'  = 3

I have these models:

  • Model Page = has one to many relation with sections (Page-> has many sections)
  • Model Section = has one to many relation with requirements (Section-> has many requirements)

Query statement:

 $ids_array = array_pluck($orderList, 'id');
 $ids_string = implode(',', $ids_array);

 DB::statement(DB::raw('set @rownum=0'));
 
 $result = $page->sections()->requirements()->whereIn('id', $ids_array)
                  ->orderByRaw("FIELD(id, {$ids_string})")
                  ->update([
                     'sortOrder' => DB::raw('@rownum  := @rownum  + 1'),
                  ]);

I want to get all the sections and requirements and only update the requirements in the given IDs.

But when I try to update using this query, I am getting an error:

"Method Illuminate\Database\Query\Builder::requirements does not exist."

Ranx99 left a reply on Update Different Rows With Different Values In One Query! • 4 days ago

OK I have done it , In tow ways..

  • 1 ( this one is what I was looking for ) : thanks to @Tray2
$ids_array = array_pluck($commentsOderdListData, 'id');
$ids_strings = implode(',', $ids_array);

DB::statement(DB::raw('set @rownum=0'));

$result = $post->comments()->whereIn('id', $ids_array)
->orderByRaw( DB::raw("FIELD(id, $ids_strings)") )
->update([
    'sortOrder' => DB::raw('@rownum  := @rownum  + 1')
]);
  • 2 ( which uses CASE Function) => set different rows with different values
$postID = 3;
$cases = [];
$ids = [];
$params = [];

foreach ($commentsOderdListDataas $index => $array) {
    $id = (int) $array['id'];
    $cases[] = "WHEN `id` = {$id} then ?";
    $params[] = $index;
    $ids[] = $id;
}

//array to string
$ids = implode(',', $ids);

//add a space between each case
$cases = implode(' ', $cases);

return DB::statement("UPDATE `comments` SET `sortOrder` = (CASE {$cases} END) WHERE `post_id` = {$postID} AND `id` IN ({$ids})", $params);

17th July, 2018

Ranx99 started a new conversation Update Different Rows With Different Values In One Query! • 5 days ago

Update different rows with different values in one query!

Some example:

$commentsOderdListData = [
  ['id'=>1,'sortOrder'=> 0],
  ['id'=>2,'sortOrder'=> 2],
  ['id'=>3,'sortOrder'=> 1],
  ['id'=>4,'sortOrder'=> 3]
];

I know maybe something like this will work:

$postID = 2;
$post =  $this->model->where('id',  $postID )->firstOrFail();

foreach($commentsOderdListData as $data){
   $post->comments()->where('id'=>$data['id'])->update(['sortOrder'=> $data['sortOrder']]);
}
  • Is there a way to just update this data in one query, for best performance ?

12th July, 2018

Ranx99 left a reply on Update, Create And Delete HasMany() Relations In One Go • 1 week ago

was looking for a way to do that, thanks @davestewart

11th July, 2018

Ranx99 left a reply on Get Model's Relation By Name ? • 1 week ago

@lostdreamer_nl

thank you for the info! really helpful!

Ranx99 started a new conversation Get Model's Relation By Name ? • 1 week ago

Is there a way to call a relation by its name , Iam looking for somthing like:

$relation = 'comments';
$user->getRelation($relation )->create([]);

I have tried this, but I am getting :

"Undefined index: comments"

9th July, 2018

Ranx99 left a reply on How To Store An Array Of Strings Into One Database Field? • 1 week ago

Yes, I was trying to find a laravel's way to store an array like that.. still looking!

8th July, 2018

Ranx99 left a reply on How To Store An Array Of Strings Into One Database Field? • 1 week ago

@jlrdw

yes, so I guess it would be something like this: main table (let's call it posts table):

title
status
slug
requirements (text field) removed into a spreate table
specifications (text field) removed into a spreate table
info (text field) removed into a spreate table

requirements_posts table:

id
post_id
body_info

specifications_posts table:

id
post_id
body_info

info_posts table:

id
post_id
body_info

but doesn't this seems an overkill ?

Ranx99 left a reply on How To Store An Array Of Strings Into One Database Field? • 1 week ago

@jlrdw

Yeah I was thinking of that ( I just updated my question ) , but since I have 3 different text fields inside that table which all have the same behavior .. is it really good to separate these 3 fields into 3 separate tables, and make a foreign key between main table and each of these tables ?

Ranx99 started a new conversation How To Store An Array Of Strings Into One Database Field? • 1 week ago

Let's say I have an array:

$requirements  =  ['requirement1 bla bla',  'requirement2 bla bla',  'requirement3 bla bla'];

And I have a requirements field in database's table which is a Text data type field

What is the best way to store this array into this field and when I try to retrieve the data I will be able to do this:

requirements are: 1 - requirement1 bla bla 2 - requirement2 bla bla etc..

29th June, 2018

Ranx99 left a reply on Is Method Injection A Bad Practice? • 3 weeks ago

@bobbybouwmann

Great! Thank you for your time and help.

Ranx99 left a reply on Is Method Injection A Bad Practice? • 3 weeks ago

@bobbybouwmann

Yeah, I think I can apply it when I feel like the controller is getting heavy!

In the meantime, I found a cool way to call these action classes:

  • CallActions trait
namespace App\Library\Traits;

use App\Library\Core\ActionCaller;
use Illuminate\Container\Container;

trait CallActions
{
    public function execute($action, $data = null)
    {
        return Container::getInstance()->make(ActionCaller::class)->trigger($action, $data);
    }
}
  • Add CallActions trait to be used by all controlers
namespace App\Http\Controllers;

use App\Library\Traits\CallActions;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
   use AuthorizesRequests, DispatchesJobs, ValidatesRequests, CallActions;
}
  • ActionCaller
namespace App\Library\Core;

use Illuminate\Contracts\Container\Container;

class ActionCaller
{
    private $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function trigger($action, $data)
    {
        return $this->container->call($action, ['data' => $data], 'execute');
    }
}

  • Will be used like this
public function store(ArticleStoreRequest $request)
{
    $article= $this->execute(ArticleStoreAction::class, $request->validated());

    if ($article) {
        return redirect()->route('admin.permissions.edit', $permission->id);
    } else {
        return back();
    }
}

28th June, 2018

Ranx99 left a reply on Homestead: "ETXTBSY: Text File Is Busy" • 3 weeks ago

@phpMick

Try downgrading to [email protected]

Ranx99 left a reply on Is Method Injection A Bad Practice? • 3 weeks ago

@bobbybouwmann

Thanks you, Really interesting article .. so the author has replaced all controllers with a "single action controllers". But, doesn't that mean I will have many controllers files ?

So in case I have a crud ArticleController I would do something like

  • ArticleGetController
  • ArticlePostController
  • ArticleUpdateController
  • ArticleDestroyController

Ranx99 started a new conversation Is Method Injection A Bad Practice? • 3 weeks ago

Let's say I have these classes which will only have one method ( 'execute' ):

  • CreateAction
  • EditAction

Action classes will be used by all controllers to do the business logic and return some data to be used by the response, and I want to call these classes inside controller's methods by using Automatic Injection.

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\Posts\StoreRequest;
use App\Action\Posts\EditAction;
use App\Action\Posts\CreateAction;

class PostController extends Controller
{
    public function index()
    {
        return view('posts.index');
    }

    public function create()
    {
        return view('posts.create');
    }

    public function store(StoreRequest $request, CreateAction $action)
    {
        $post = $action->execute($request->validated());

        return redirect()->route('posts.edit', $post->id);
    }

    public function edit($id, EditAction $action)
    {
        $post =  $action->execute($id);

        return view('posts.edit', compact('post'));
    }
}

Example for EditAction :

namespace App\Actions\Posts;

use App\Models\Post;

class EditAction
{
    private $post;

    public function __construct(Post $post)
    {
        $this->model = $post;
    }

    public function execute($id)
    {
        return $this->model->where('id', $id)->firstOrFail();
    }
}
  • Is using Automatic Injection a bad practice ?
  • Is there a better way for calling these action classes ?

24th June, 2018

Ranx99 left a reply on Some Questions About ADR Pattren! • 4 weeks ago

I guess not many developers using this pattern !?

23rd June, 2018

Ranx99 started a new conversation Some Questions About ADR Pattren! • 4 weeks ago

I have read this: https://github.com/pmjones/adr

I understand the point of Actions and the Domain but:

  • Why should the Responder be separated to a new class? why just don't just do it inside the Action like this:
public function __invoke(Request $request)
{
    $data = $this->postService->getPost($request->get('id'));

    return view('post.show', compact('data'));
}
  • Has anyone tried to use this pattern in his projects? If so, what do you think about it?

14th May, 2018

Ranx99 left a reply on Homestead: "ETXTBSY: Text File Is Busy" • 2 months ago

Iam not opening any shared file on the host OS,.

npm install --no-bin-links

tried this and it gave me the same errors...

it seems to work for me when I downgrade the npm for now.

13th May, 2018

Ranx99 started a new conversation Homestead: "ETXTBSY: Text File Is Busy" • 2 months ago

Iam doing a fresh laravel project install with latest versions of:

  • lalravel homestead box (v6.0.0)
  • vagrant (2.1.1)

Iam using "windows 10" as Host.

now when I do "npm install" to install the dependencies, I get many errors :

npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/abbrev/package.json.1705314388'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/acorn/package.json.1138498880'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ajv-keywords/package.json.1663198334'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/acorn-dynamic-import/node_modules/acorn/package.json.1356440482'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/acorn-dynamic-import/package.json.2699619638'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/alphanum-sort/package.json.548391976'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/adjust-sourcemap-loader/node_modules/camelcase/package.json.2204453570'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/amdefine/package.json.3206824631'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ansi-html/package.json.158893468'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ansi-wrap/package.json.3041354002'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ansi-gray/package.json.2281624877'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ansi-regex/package.json.212328612'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/aproba/package.json.1062736441'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/archive-type/package.json.970322693'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/arr-diff/package.json.3131142389'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/archive-type/node_modules/file-type/package.json.2364150964'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/arr-flatten/package.json.827426214'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/arr-union/package.json.1072950859'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-differ/package.json.970724807'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-flatten/package.json.2479398186'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-find-index/package.json.2102662261'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-uniq/package.json.3261859398'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-union/package.json.973410432'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/asn1/package.json.3390038911'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/assert-plus/package.json.626536117'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/array-unique/package.json.367793859'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/assign-symbols/package.json.3997474815'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/async-each/package.json.2150029441'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/ast-types/package.json.1509703659'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/async-each-series/package.json.1231243004'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/async-foreach/package.json.165440910'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/atob/package.json.2465016514'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/asynckit/package.json.2102742188'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/aws-sign2/package.json.1582875451'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/aws4/package.json.3284052633'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-core/node_modules/source-map/package.json.602266737'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-code-frame/node_modules/ansi-styles/package.json.2393111773'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-generator/node_modules/source-map/package.json.52151904'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-code-frame/node_modules/supports-color/package.json.3230894599'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-plugin-syntax-async-functions/package.json.579433913'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-plugin-syntax-exponentiation-operator/package.json.3383012636'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-plugin-syntax-object-rest-spread/package.json.1039671854'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-plugin-syntax-trailing-function-commas/package.json.2830802730'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babylon/package.json.3244942865'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/balanced-match/package.json.3865753112'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/base64-js/package.json.2189141935'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/batch/package.json.1015925448'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/big.js/package.json.1320199066'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/beeper/package.json.2703642682'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-code-frame/node_modules/supports-color/package.json.3230894599'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-generator/node_modules/source-map/package.json.52151904'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/babel-core/node_modules/source-map/package.json.602266737'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/adjust-sourcemap-loader/node_modules/camelcase/package.json.2204453570'
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/code/site1/node_modules/bin-build/node_modules/uuid/package.json.1347906736'
npm WARN [email protected] requires a peer of [email protected]^6.0.0 but none is installed. You must install peer dependencies yourself.

npm ERR! path /home/vagrant/code/site1/node_modules/alphanum-sort/package.json.548391976
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename
npm ERR! ETXTBSY: text file is busy, rename '/home/vagrant/code/site1/node_modules/alphanum-sort/package.json.548391976' -> '/home/vagrant/code/site1/node_modules/alphanum-sort/package.json'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2018-05-13T08_28_36_234Z-debug.log

Anyone else facing this ?

Ranx99 left a reply on Homestead Npm Install --no-bin-links Error • 2 months ago

Same issue for me too! (windows as host)

  • adding (--no-bin-links) didnt work.
  • open cmd as admin didnt work.

Iam runing npm v6.0.0...

any one found out a way to solve this ?

15th March, 2018

Ranx99 left a reply on Solutions For Uploading Large Files ? • 4 months ago

I just found a package that does all this, created by @kfirba, which will generate a signature to be used for Fineuploader and many more.. its really useful.

14th March, 2018

Ranx99 left a reply on Solutions For Uploading Large Files ? • 4 months ago

@Snapey thank you. I have checked the blog's post real fast and it seems It has what Iam looking for..

gonna play with it tonight and maybe trying to create a package for who wants to use fineuploader like me.

Iam wondering how does Laravel generate a signature when using the integrated s3 storage ?

Ranx99 left a reply on Solutions For Uploading Large Files ? • 4 months ago

Yes, "Fineuploader" has this feature which will upload files without passing it to your server then s3. so It will be direct to s3.

https://docs.fineuploader.com/endpoint_handlers/amazon-s3.html

but In order to do so . I need to generate a signature for using s3 service directly .. which where Iam stuck with ..

I have checked "vue-s3-dropzone" but It doesn't provide the features I want as "Fineuploader" does.

12th March, 2018

Ranx99 started a new conversation Solutions For Uploading Large Files ? • 4 months ago

In the past few days I was trying to find a nice way to handle this, and came a cross:

"fineuploader" https://fineuploader.com

which can be used to upload these kind of files ( large files: 1GB something ) directly to s3 .. and I think this is the way to go for .. but Iam stuck on how to do this along with "Vue" and "Laravel" ... if there is some examples on how to handle this or what steps to follow .. i would appreciate it..

26th January, 2018

Ranx99 left a reply on Single Login System For Mobile And Web App !? • 5 months ago

I think I need to just separate the login and just add CreateFreshApiToken for web guard and that's it ??

As for mobile I should return json ( access token and refresh token to be used in each request ) ..

Does this seems right ?

Ranx99 left a reply on Single Login System For Mobile And Web App !? • 5 months ago

so, I dont need to store access token and refresh token" for any next API requests into a session .. that will be handled by CreateFreshApiToken !?

25th January, 2018

Ranx99 started a new conversation Single Login System For Mobile And Web App !? • 5 months ago

Can I use API and Passport for single login system for web app ( MPA ) and mobile native app ?

  • As for WebControllers guarded by "web" I will store the "access token and refresh token" for any next API requests ( I want to consume the same API that is used by the mobile app) and user info would also be stored into a session ..

  • As for ApiControllers guarded by "api" it will just return access token to be used by the mobile native app for any next API requests ..

Can this be possible? Is this workflow is right ? and what is CreateFreshApiToken middleware role in here ?

23rd January, 2018

Ranx99 started a new conversation API Consumed By Web And Mobile Apps !? • 5 months ago

I am confused how can this be possible ...

what I have for now is:

web.php

Route::group(['namespace'  => 'WebControllers\Front',], function () {
    Route::get('/', '[email protected]')->name('index');
});

api.php

Route::group(['prefix' => 'v1', 'namespace'  => 'ApiControllers\Front'],function(){
    Route::post('register', '[email protected]')->name('register');
    Route::post('login', '[email protected]')->name('login');
});

AuthController.php

namespace App\Http\Controllers\ApiControllers\Front;

use App\Http\Requests\Auth\RegisterRequest;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Services\Api\Front\AuthService;


class AuthController extends Controller
{
    private $authService;

    public function __construct(AuthService $authService) {
        $this->middleware('guest');
        $this->authService = $authService;
    }

    public function login(LoginRequest $request)
    {
        return $this->authService->login($request);
    }

    public function register(RegisterRequest $request)
    {
        return $this->authService->register($request);
    }
}

LoginRequest.php

namespace App\Http\Requests\Auth;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required|string|email|max:255',
            'password' => 'required|string|min:6',
        ];
    }
}

authService.php

namespace App\Services\Api\Front;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use GuzzleHttp\Client;
use App\Exceptions\InvalidCredentialsException;
use Illuminate\Support\Facades\Cookie;

class AuthService
{
    const REFRESH_TOKEN = 'refreshToken';

    public function register($requestData)
    {
        $data = $requestData->all();
        $data['password'] = bcrypt($data['password']);
        $user = User::create($data);
        return response()->json([
            'data' => [
                'message' => 'Register success!'
            ],
        ]);
    }

    public function login($requestData)
    {
        return $this->attemptLogin($requestData['email'], $requestData['password']);
    }

    /**
     * Attempt to create an access token using user credentials
     *
     * @param string $email
     * @param string $password
     */
    public function attemptLogin($email, $password)
    {
        $user = User::where('email', $email)->firstOrFail();

        if (!is_null($user)) {
            return $this->loginProxy('password', [
                'username' => $email,
                'password' => $password
            ]);
        }
    }

    /**
     * Proxy a request to the OAuth server.
     *
     * @param string $grantType what type of grant type should be proxied
     * @param array $data the data to send to the server
     */
    public function loginProxy($grantType, array $data = [])
    {
        $data = [
            'username'      => $data['username'],
            'password'      => $data['password'],
            'client_id'     => env('PASSWORD_CLIENT_ID'),
            'client_secret' => env('PASSWORD_CLIENT_SECRET'),
            'grant_type'    => $grantType
        ];

        $client = new Client();
        
        $response = $client->post(route('oauth.token'), [
            'form_params' => $data
        ]);


        if ($response->getStatusCode() != 200) {
            throw new InvalidCredentialsException();
        }

        $data = json_decode($response->getbody());

        // Create a refresh token cookie
        Cookie::queue(Cookie::make(
            self::REFRESH_TOKEN,
            $data->refresh_token,
            864000, // 10 days
            null,
            null,
            false,
            true // HttpOnly
        ));

        return [
            'access_token' => $data->access_token,
            'expires_in' => $data->expires_in
        ];
    }
}

and it works fine and outputting 'access_token' and 'expires_in'

what Iam confused about is:

  • let say I want to display the username in "[email protected]" view, which is proteccted by "web" middleware, how can I do that ?
namespace App\Http\Controllers\WebControllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class HomeController extends Controller
{
    public function index()
    {
        return view('index');
    }
}
@if (Auth::check())
<h1>{{ Auth::user()->username }}</h1>
@else
<h1>not authenticated via Passport</h1>
@endif
  • Iam logging users in using API and Passport which means I cant use sessions in my app? only tokens .. right ?
  • can I use sessions and passport with singe login via API ?
  • Iam splitting my controllers to ApiControllers and WebControllers controllers .. so WebControllers will return views and ApiControllers will return json , also WebControllers will consume the same API routes consumed by ApiControllers .. so I can only write my logic once inside services classes which will return json only responses for both ApiControllers and WebControllers .. so a mobile native app will talk to ApiControllers and web app will talk to WebControllers. is this the right way to do it?

Iam trying to learn, so bear with me :)

2nd January, 2018

Ranx99 left a reply on Best Way To Structure An Application For Mobile And Web? • 6 months ago

@martinbean

by "structure" I mean, If I used API routes(for mobile requests) and web routes(for web requests), then should I separate my controllers to:

API controllers (controllers will return json data only) web controllers (controllers will return views)

OR

If I only used API routes (for both mobile requests and web requests), then all my requests and controllers will only return json data, It will not return views. If I rquests some api route from web, how can I display this data coming from the controller since Iam not returning any view !

Iam confused .. hope I explained this well, and sorry for my english :)

Ranx99 left a reply on Best Way To Structure An Application For Mobile And Web? • 6 months ago

@martinbean I mean native app

Ranx99 started a new conversation Best Way To Structure An Application For Mobile And Web? • 6 months ago

Iam building a big application using laravel + vue for learning purposes .. now, lets say in the future I want to build a mobile version for it. with keeping in mind all my routes are inside wep.php for now.

  • Should I convert my current routes and use single APIs for both web and mobile for all requests?
  • if I did that, how can I distinguish between mobile request and web request, so if its web request It will return view, otherwise return json.

Whats the best way to approach this?

16th December, 2017

Ranx99 left a reply on Best Way To Handle Status Field !? • 7 months ago

@PovilasKorop

thats what I was thinking (it will be much easier to add a new status in the future ) , but why didn't you use only one master status table for all , not users_statuses , posts_statuses etc ..

Ranx99 left a reply on Best Way To Handle Status Field !? • 7 months ago

@bobbybouwmann what about using a separate table for status and store status_id to each table

Ex: users table:

  • id
  • name
  • email
  • password
  • status_id

Ranx99 started a new conversation Best Way To Handle Status Field !? • 7 months ago

If I have users,articles and categories models. now, each model will have a status value stored inside database ..

Ex:

  • users would have (active, expired, etc)
  • articles would have (published, active, draft, etc)
  • categories would have (enabled, disabled, etc)

what is the best way to do it ..

should I store status field directly using tinyint datatype:

Ex:

users table:

- id
- name
- email
- password
- status // comment : 0 = expired, 1 = active, etc

posts table:

- id
- title
- desc
- status // comment : 0 = draft, 1 = active, 3 = published etc

should I use one single status table and use foreign key status_id to each table ...

Ex: status table

- id
- name ( active, expired , published, draft, archived .. etc )

13th December, 2017

Ranx99 left a reply on Validate Array Values !? • 7 months ago

should I be use Validator::make to make it work !?

Ranx99 started a new conversation Validate Array Values !? • 7 months ago

I want to check some values inside an array if they are unique in some database tables column:

selectedCruds fields request:

array:4 [▼
  0 => "create-course"
  1 => "edit-course"
  2 => "update-course"
  3 => "delete-course"
]

Now I want to check if the values are unique inside permissions table,name..

I tried this but its not working :

$this->validate(
            $request,
            [
            'selectedCruds.*'=>'unique:permissions,name',
            ]
        );

am I using (.*) right !?

10th December, 2017

Ranx99 left a reply on Load Components Only When Are Required !? • 7 months ago

ok , I have found a way for this with vue "Async Components"

https://vuejs.org/v2/guide/components.html#Async-Components

1- install babel syntax-dynamic-import plugin

npm install --save-dev babel-plugin-syntax-dynamic-import

2- add this to ".babelrc" file, If you dont have one .. create one in project root

{
  "plugins": ["syntax-dynamic-import"]
}

3- use Async Components

Vue.component('component1', () => import('./components/Component1.vue'))

4- add this to "webpack.mix.js" so you can store your components inside public/js

mix.webpackConfig({
    output: {
        publicPath: '/',
        chunkFilename: 'js/[name].[chunkhash].js',
    }
});

components now will load on demand only.

9th December, 2017

Ranx99 started a new conversation Load Components Only When Are Required !? • 7 months ago

I am building a laravel MPA "traditional" not SPA using Vue. Now Iam using only one "vue" instance for my app , which will load all the "components .vue" that are needed inside my app ...

main.js


require('../bootstrap');

window.Vue = require('vue');

Vue.component('component1', require('./components/Component1.vue'));
Vue.component('component2', require('./components/Component2.vue'));
Vue.component('component3', require('./components/Component3.vue'));
//etc........

const app = new Vue({
    el: '#app',
});

My problem:

lets say I have 20+ vue components and I opend my app "Homepage", my "main.js" will load all the 20+ vue components which are not needed by this page.. and this will make "main.js" file size bigger

Iam looking for a way which is more dynamic that makes components could load on demand.

11th November, 2017

Ranx99 left a reply on Different Fields Based On User Role • 8 months ago

hmm after playing with polymorphic relations I had it working like this:

database will look like this:

"users" table

-  id
-  email
-  password
-  userable_id
-  userable_type
-  common fields by all the roles ...

"employees _users" table
-  id
-  about_me
-  some other unique fields for employees role

first creating a new service provider and adding "morphMap"

public function boot()
    {
        Relation::morphMap([
            'employee' => 'App\Employee',
        ]);
    }

in App\Employee model:

class Employee extends Model
{
    public function user()
    {
        return $this->morphOne('App\User', 'userable');
    }
}

10th November, 2017

Ranx99 left a reply on Different Fields Based On User Role • 8 months ago

I read about polymorphic relations and that its more "the right way" to do it .. but polymorphic relations is not clear to me..

could someone explain how that will work ? with roles and users ? https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations

or should I do it like in my first post without polymorphic relations!!

Ranx99 started a new conversation Different Fields Based On User Role • 8 months ago

well, Iam using laravel-permission package by spatie https://github.com/spatie/laravel-permission

To mange roles and permissions

My question is: lets see I have 3 roles: admin, employee and manger.

now each one of these roles has its own unique fields!

"users" -email -password

  • common fields by all the roles ...

I was thinking of creating something like this :

"employees _users" table user_id about_me some other unique fields for instructors role

"mangers _users" table user_id url some other unique fields for mangers role

is this right ?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.