ronon

Experience

13,070

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 100 Lessons Completed
  • 1 Favorite

22nd August, 2018

ronon started a new conversation Trait Not Found • 4 weeks ago

I have read many other threads regarding this issue, but nothing helped.

I'm using laravel 5.5 and for the passwordreset is overwrote the setPasswordAttribute function

User extends Authenticatable{
public function setPasswordAttribute($value)
    {
            $this->attributes['password'] = bcrypt($value);
    }
}

Now I had to modify the ResetPasswords file, because i had to change this line

        $user->password = Hash::make($password);

to this

$user->password = $password;

I have a folder for traits under App\Traits.

I copied the whole content from ResetsPasswords to App\Traits\ResetsPasswordTrait and modified the line

<?php

namespace App\Traits;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Foundation\Auth\RedirectsUsers;

trait ResetsPasswordsTrait
{
    use RedirectsUsers;

    [...]

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $user->password = $password;

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));

        $this->guard()->login($user);
    }

[...]
}

I updated the trait in ResetPasswordController

<?php

namespace App\Http\Controllers\Auth;

use App\Traits\ResetsPasswordsTrait;
use App\Http\Controllers\Controller;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswordsTrait;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

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

I have other Traits in the foler as well which are working which are working but for this one I always get a Trait not found exception. I executed composer dump-autoload and php artisan clear:cache but I cannot get rid of it. What's wrong with my code?

14th August, 2018

ronon left a reply on Change Form Of Address Efficiently • 1 month ago

Thats not what I'm looking for. The authorization is working as it should. I have many parts where I need to change the phrase the user sees depending on if the user is visiting his own profile or not. I think it's suboptimal to do it like

if(auth->id == $user->id)
  print this
else 
    print that

those checks in the blade files is getting too much, need to refactor it to a better way to do it

ronon started a new conversation Change Form Of Address Efficiently • 1 month ago

I need to change the form of address depending if the owner is visiting his profile or if anyone else is visiting it.

Is there a better way than do it like

@if(auth()->id() === $user->id)
       Your friends
@else
    Friends of $user->name
@endif 

The string are located in language files.

I thought of an one liner, maybe like

echo getFormOfAddress('string for owner', 'string for foreigners', $user(?));

function getFormOfAddress($owner, $foreigner, $visitedUser){
    return ($visitedUser->id === auth()->id()) ? $owner : $foreigner;
}

but i guess there might be a better way to do it with laravel where i'm not aware of.

Maybe someone knows a better solution for it :)

16th July, 2018

ronon started a new conversation Override Can Policy Response • 2 months ago

I use Policies to check if an user has the permission to perform an action. For the api endpoint I need to put that response in a specific format.

If a user who is not allowed to view messages for a message Route::get('/{message}/messages', '[email protected]')->middleware('can:view,message')

it throws a 403 error.

But I need to have it as a json ouput like:

{
    error: true,
    msg: 'Unauthorized'
}

How can I override it?

24th June, 2018

ronon started a new conversation Log In Scheduled Tasks Breaks API. Only Log From Tasks Appear In Log File • 2 months ago

On a website i have an API api.example.com and approx. 12 scheduled tasks. Some of these tasks run once daily, others every minute or hourly. If I use Log::debug, Log::info, Log::error in one of these tasks the api endpoint breaks completly and I receive 500 - Server errors and no further error message in the logs, neither in nginx nor laravel.

The website is usable as always, but also won't write anything to the log. Only the Log:: from the tasks occur in the log.

What causes this behaviour?

I use daily logs with log_level debug.

ronon left a reply on User Session In API Response • 2 months ago

If you use any kind of authenthication, you are authenticated. So you even don't need to use Auth::check

23rd June, 2018

ronon left a reply on User Session In API Response • 2 months ago

You can use Auth::check on the API side as well.

13th June, 2018

ronon left a reply on NPM Installing Scripts And Then Running Them On My Blade Template • 3 months ago

the php section is the wrong way for this.

How it should work.

  1. npm install --save toastr

  2. Include in your resources/assets/js/app.js file.

  3. compile it npm run watch see https://laravel.com/docs/5.6/mix#running-mix for options like production/dev

  4. include the js file from your public/js/app.js at the end of your body.

Use it toastr.info('Are you the 6 fingered man?')

Don't forget to include the css file!

8th June, 2018

ronon started a new conversation How To Use PECL/Pear Extensions In Laravel? • 3 months ago

I need to use pecl/pear extension in my laravel app, but I really don't have a clue how to include them the proper way.

For example this package: http://pear.php.net/package/Net_CheckIP/docs/latest/Net_CheckIP/Net_CheckIP.html

Where do I have to place the require_once "Net/CheckIP.php"; so it works in laravel?

I know that to use require_once in a controller is a nogo.

21st May, 2018

ronon left a reply on Merge Two Huge Collections 10k+ Items Each, One Is An Eloquent Collection The Other An [array] Collection • 3 months ago

This is why i chunked it to 1000 values each round.

ronon started a new conversation Merge Two Huge Collections 10k+ Items Each, One Is An Eloquent Collection The Other An [array] Collection • 3 months ago

I have two collection. One is an eloquent collection files and the other one is a file array converted to a collection.

I need to lookup if the file array is already in the database and append some attributes to the file array. For example if the file exists in the database, if the file was modified etc..

// create collection from files array
$collection = collect($files);

// First idea
// Chunk it, so the eqloquent collection is smaller
foreach($collection->chunk(1000) as $chunk){

      // ID list for db query
    $ids = $chunk->pluck('file_id')->toArray();
       
        $files = File::whereIn('file_id', $ids)->get();

       foreach($chunk as $file){
          
             // Here it gets tricky
             // I need to check if the file exists in the $files collection
            // I tried it with
            $found = $files->where('file_id', $file->file_id)->first();
            // But the execution time exceeds

           if(!is_null($found)){
                 // Add some values, like, etc...
                $file->existsInDb = true;
                $file->created_at = $found->created_at;
             } else {
               $file->existsInDb = false;
                $file->created_at = -1;
             }
      }

return $files;
}

file_id is type of string and unique.

How can I improve the $found = $files->where('file_id', $file->file_id)->first(); search in the collection part?

If i make a query for each File i receive an 504 Gateway Timeout, so I think the database don't like that approach.

Might there be a much better approach for this problem?

ronon left a reply on Generate Multidimensional Array From Singledimensional Array, Entry Only Nows It's Parent • 3 months ago

@jlrdw The dataset didn't come from the database, so wasn't an option

@hjgarcia1 You brought me on the correct path. Had to do it as tree. Thanks for that :)

This solution worked for me https://stackoverflow.com/a/22020668

ronon started a new conversation Generate Multidimensional Array From Singledimensional Array, Entry Only Nows It's Parent • 3 months ago

I have the following array

[
    [
         name = 'Root',
    id= 1,
    ],
    [
         name = 'Images',
    id= 456,
        parent_id = 1
    ],
    [
         name = '2018',
    id= 5756,
        parent_id = 456
    ],
    [
         name = 'uploads',
    id= 45879,
        parent_id = 5756
    ],
    [
         name = '2017',
    id= 534,
        parent_id = 456
    ],
etc..
]

It's a single dimensional array. Each entry only nows its parent according to the given id. The parent doesn't knows if it has children until you visit it.

How can I create an mutlidimensionales array like


$arr['Root']['Images']['2018']['uploads'];
$arr['Root']['Images']['2017'];

To clarify, i need the following structure.

Root
  - Images
     - 2018
       - uploads
          - more folders
    - 2017
     - wedding
     - vacation
        - toSort
  - Videos
    - Funny
    - Movies
      - Action

etc.

I can only archieve it till level 2Images

 $data = [];
        foreach($folders as $folder){

            // Parent directory
            if(empty($folder->parent_folder)){
                $data [$folder->name]['id'] = $folder->id;
                $data [$folder->name]['name'] = $folder->name;
            } else {

                // Get all parent folders for the given folder
                $parents = array_reverse($this->parentFolder($folder));
        
        // How to go further?
              // Use the parents as access key??

            }

        }

18th May, 2018

ronon left a reply on Disable HTML Ouput For API And Prevent API From Redirecting. 302 And 500 "bugs" • 4 months ago

Had to add Accept application/json to it

17th May, 2018

ronon started a new conversation Redis Sorted Hashes On Score Like In Sorted Sets Zrange • 4 months ago

I'm writing kind of a firewall for laravel. I'm using redis to prevent performance issues.

I need to store the counts on a daily base. So i have to be able to access the current count of a specific key:value base. I came up with hashes, like

Redis:hincrby($key, $ip, 1);

So i can access the value

Redis::hget($key, $ip);

But for statistic issues i would like to get the ips with the most hits.

How can i get the top x hits, like it is possible with sorted sets?

Redis::zrange(0, 10, WITHSCORES);

Do i need to store the hits additionally in a sorted set, or is there a way to achieve this behavior with hashes as well? Or do I need to use a different type? Or is there a way to access a entry in a sorted set like in a hash?

15th May, 2018

ronon left a reply on Custom Exception Handler Throws Exception Instead Of Parsing It • 4 months ago

Ahh now i understand it, thanks for the clarification :)

ronon started a new conversation Custom Exception Handler Throws Exception Instead Of Parsing It • 4 months ago

I need to modify the response of the ValidationException so I created myself an exception.

namespace App\Exceptions;

use Exceptions;

class ValidationException extends Exception
{

    public function __construct($message){
        parent::_construct($message);
    }
}

I also added my Exception to Handler.php

<?php

namespace App\Exceptions;

use App\Utils\ResponseUtil;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
        ValidationException::class
    ];


    public function report(Exception $exception)
    {
        parent::report($exception);
    }

 
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(ResponseUtil::makeError('Unauthenticated.'), 401);
        }

        return redirect()->guest(route('login'));
    }
}

If i call it now in a Request


<?php

namespace App\Http\Requests\Api;

use App\Exceptions\ValidationException;
use App\Models\User;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest extends FormRequest
{
   
    public function authorize()
    {
        return true;
    }

   
    public function rules()
    {
        return User::$rules;
    }

    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException('Validation failed at register process'));
    }
}

But it throws an exception for the ValidationException.

If i add a render method to my ValidationException and return a response it works.

Do I have to apply a render method to it? As far as i understood I have to add my exception to the $dontReport array in Handler.php, also that render method should be called, or am I totally wrong?

6th May, 2018

ronon left a reply on Share Image On Multiple Sites After Image Job Is Processed • 4 months ago

I would like that the sites are processed kinda parallel. So I think creating a new job for each site would be the better way?!?

ronon started a new conversation Start, Stop, Pause, Remove On A Running Job In A Queue • 4 months ago

Is it possible to perform those actions, start if paused, stop, pause and remove, on a running job in a queue?

Couldn't find anything related to this.

ronon started a new conversation Share Image On Multiple Sites After Image Job Is Processed • 4 months ago

A user can upload any amount of images to a server. There the image is stored in the database and processed afterwards.

The user can select mutliple services before the upload, which tells the script, where he wants to share the image. FB, Twitter, etc...

First step I store the image in the database:

Image::create([values]);

Next I convert and resize the image with a job and chain it with the ShareImage job

ProcessImage::dispatch($image);

But now that the user can select only the sites where he wants to share the image, i don't know how to create a job for each site the image should be shared on.

Should I chain the jobs and the last job creates new jobs for each site?

ProcessImage::dispatch($image);->chain([
    new ShareImage($image)
]);

ShareImage

class ShareImageimplements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $image;
    protected $sites;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Image $image, $sites = [])
    {
        $this->image= $image;
    $this->sites = $sites;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        foreach($this->sites as $site){
        // Determine the site with a Factory
              // Now generate a job for it, or....? 
    }
    }
}

Would this be a good approach or...?

I thought about creating the chain array dynamically, but this would make each site dependent from the previous job, right? Or is there a way to create only from the main job dependable jobs?

3rd May, 2018

ronon left a reply on Broadcasting - Pusher • 4 months ago

Dou you start the worker so the queue is processed?

25th April, 2018

ronon started a new conversation Abort Request If Requested On Subdomain Instead Of Showing Hte Content • 4 months ago

I have an api for an website which works fine. Now I have the problem, that a user can use for example api.example.com and gets the same site as if he would visit example.com. I just have a few routes registered in the routes\api.php file. All other routes are located in routes\web.php.

The RouteServiceProvider

/**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('v1')
             ->middleware(['api', 'auth:api', 'permission:use api'])
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

How can I return an error like 403 Forbidden or sth else. Is there an way to do this in laravel directly or do I have to modifiy the nginx config file?

I have two nginx config files. One for the main site and one for the api. Both are hosted on the same server and share the same directory like var/html/laravel/myapp The difference is, that nginx should use a different php-fpm pool for api so the main pool doesn't get affected by the api requests.

api.php

Route::domain('{api}.'.config('app.url'))->group(function () {
    
    Route::get('/user', function (Request $request) {

        return $request->user();
    });

});

24th April, 2018

ronon started a new conversation Disable HTML Ouput For API And Prevent API From Redirecting. 302 And 500 "bugs" • 4 months ago

I have written an API for a site. It uses the api_token as user validation.

In my test all works fine but in production I get sometimes an 302Redirect to api.example.com/. Here I get the same page as if I visit example.com/.

I really don't have a clue why I sometimes get an redirect and sometimes not. If I use the url from the access log and past it in the browser it works fine.

How can I disable the redirect for the api subdomain and just throw an error like Unauthorized or sth else. The best would be if it would be an json string.

Next problem is that some endpoints are time consuming. Most of time finish "in time" but I think some exceed it and it throws the laravel 500 html error page. No error in the nginx logs nor in php log.

ronon left a reply on Add A Where Clause Into A Has Clause • 4 months ago

@devk yes that works as expected. Thanks :)

@Helmchen This wouldn't allow to filter through the count option

ronon started a new conversation Add A Where Clause Into A Has Clause • 4 months ago

I have two models. User and Images. Now I want to get the users with the pictures in a category. A User is in relationship with Images through a hasMany relation.

I can get the users with at least x images

User::has('images', '>', $x);

and the query looks like

select * from `user` where (select count(*) from `images` where `users`.`id` = `images`.`imageable_id` and `images`.`imageable_type` = ?) > 50

but I need to add the category to the has clause. So I need to add a clause, so the query looks then like:

select * from `user` where (select count(*) from `images` where `users`.`id` = `images`.`imageable_id` and `images`.`imageable_type` = ? AND category = "my_category") > 50

How can I achieve this behavior?

31st March, 2018

ronon left a reply on Running Multiple Long Ranning Tasks Like Video Conversion At Once • 5 months ago

Will try it. I appreciate your help :)

29th March, 2018

ronon left a reply on Running Multiple Long Ranning Tasks Like Video Conversion At Once • 5 months ago

Doing it manually with supervisor. How would I run multiple queue workers? Would they interfer with getting the jobs?

ronon started a new conversation Running Multiple Long Ranning Tasks Like Video Conversion At Once • 5 months ago

Hi,

I need to develop a website where users can upload and convert videos. My plan was to add the files to a queue and process one after another. So far so good, but the server has a lot of cores 32+ and one encoding process would be inefficient, so I would like to have x = 4 encoding processes at a time. The queue can have hundrets of entries per server.

So whats the best way to run x encoding processes at once?

Hope someone has some helpful hints :)

ronon left a reply on What's The Best Way To Conditionally Hide Certain Properties Of A Relationship? • 5 months ago

The best way I think is that you should use policies https://laravel.com/docs/5.6/authorization#authorizing-actions-using-policies and add the corresponding fields to your json response

11th March, 2018

ronon left a reply on Policy Not Working On Route Middleware, Works In View • 6 months ago

I forgot to add the User model on [email protected]. Had only function(Request $request) instead of function(Request $request, User $user)

ronon started a new conversation Policy Not Working On Route Middleware, Works In View • 6 months ago

I try to use a policy on multiple routes but it seems that the specific policy function isn't called and I receive and 403 Unauthorized exception.

Policy

<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Auth;

class UserPolicy
{
    use HandlesAuthorization;

    public function update(User $authUser, User $user)
    {
        return $authUser->id === $user->id;
    }

}

Policy registration:

class AuthServiceProvider extends ServiceProvider
{

    protected $policies = [
        'App\Models\User' => 'App\Policies\UserPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();
    }
}

web.php

Route::patch('/user/{user}/update', '[email protected]')->middleware('can:update,user')->name('user.update');

I tried to dd()in the update() method but it didn't show any output.

If a logged in user visits the profile of another user I check it with @can('update', $user) and it works as it's supposed to be.

8th March, 2018

ronon started a new conversation How To Set The Redis Session Driver? • 6 months ago

On a site I expierence a lot of

","exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction (SQL: update `sessions` set `payload` = payload `last_activity` = 1520538614, `user_id` = USERID, `ip_address` = IP_ADDRESS, `user_agent` = USERAGENT where `id` = SESSION_ID) at /var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\DBAL\Driver\PDOException(code: HY000): SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction at /var/www/html/laravel/vendor/doctrine/dbal/lib/Doctrine/DBA

At time of writing there are about 76k active sessions in the database.

I read a lot of articles on stackoverflow and elsewhere but couldn't find a solution for it. So I thought It would be good to store the sessions in the faster Redis Server but I won't get it to configure it correctly.

In my .env file I changed from database to SESSIONDRIVER=redis. But how do i specify a redis connection in the session.php file?

My database.php looks like:


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),



    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'hds'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
        ],

    ],


    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

If I set the 'connection' => redis, it throws Database [redis] not configured. error. I'm using Redis as Cache, so a connection should already exists, or am I missing sth?

ronon started a new conversation Show Images In Gallery And On User Profile, Without BelongsToThrough Relation • 6 months ago

I have the following problem. I have three models User, Image and Gallery. The images table contains all images ever uploaded. For example avatar images, and so on.

I have the following relations:

class User extends Model {
    
    public function images(){
        return $this->hasMany(Image::class);
    }
}


class Image extends Model {
    
    public function user(){
        return $this->belongsTo(User::class);
    }
}


class Gallery extends Model {
    
    public function images(){
        return $this->hasMany(Image::class);
    }
}

Now I have a few problems:

  1. How should I assing the images to the Gallery? An Image belongs to only one Gallery.
  2. I need to display the images on the user profile WITHOUT the gallery. Just the plain images. It could be that the gallery gets deleted, but without the images, they need to be visible on the user profile at all. So a belongsToThrough relation won't work.

Should I do it with a polymorphic relation, or... I currently don't have a plan.

27th February, 2018

ronon left a reply on Accesor With Relation, Property Error • 6 months ago

Thanks for the hint. That works, so i think it's a naming issue. Can anyone prove me wrong?

26th February, 2018

ronon started a new conversation Accesor With Relation, Property Error • 6 months ago

If have two models. Image and User.

User is related to Image like this:

public function profileImage()
    {
        return $this->hasOne(Image::class, 'image_id', 'profile_image_id');
    }

Now I want to retrieve the correct url for the profile image.

I tried it with:

public function getProfileImageAttribute()
    {
        if(!empty($this->profileImage)){
            return Storage::disk('storage')->url($this->profileImage->file_id);
        }
        return 'http://via.placeholder.com/150?text=' . substr($this->firstname, 0, 1) . substr($this->lastname, 0, 1);
    }
```

But this doesn't work. 

If I make a `dd($this->profileImage)` in `getProfileImageAttribute()`, I receive 
`Undefined property: App\Models\User::$profileImage`

Is it a naming issue, because I have the relation named `profileImage` and the accessor `getProfileImageAttribute`, or where exaclty is the problem? If I'm not totally wrong the accesor is accessed like `$user->profile_image` ?

25th February, 2018

ronon left a reply on Custom Validation Error Messages For Min,max,size • 6 months ago

message
    :   
Undefined index: string
exception
    :   
ErrorException

I need to send an specific error code:

'email.max' => [
                'errorcode' => 401,
                'message' => 'Too long'
            ]

It works without array, but with it won't work. The array response works for required unique, etc...

ronon left a reply on Custom Validation Error Messages For Min,max,size • 6 months ago

I know the docs. But there is nowhere mentioned how to do it for min, max and size

ronon started a new conversation Custom Validation Error Messages For Min,max,size • 6 months ago

How can i set a custom error message for the types min, max, size?

If I try

'value.min.string'  => 'Too short'

I receive the default message and If I try

'value.min'  => 'Too short'

It throws an error.

What am I doing wrong?

17th December, 2017

ronon started a new conversation Best Way To Implement Roles And Permissions? • 9 months ago

I'm using laravel backpack for a site with the permissionmanager from Spatie https://github.com/spatie/laravel-permission .

I have different roles, like admin, moderator, user, etc. What's the best way to implement the roles and permissions in my application?

Should I use middlewares? Should I call the constructor and check the permissions there? Admins for example can do litteraly everything. Moderators not and user just have a few permissions.

I really don't have a clue at the moment.

I'm using permissions for the first time so please apologize the noobish questions.

I'm thankfull for every advice/help.

14th December, 2017

ronon started a new conversation Use The History Mode With Laravel And Vue / No SPA • 9 months ago

I kinda have a"normal" website, no SPA or sth stuff. I'm using vue with vuetify to display some of the elements. Now if the user clicks on a button I load content via ajax (axios) from the server and display it in a corresponding div.

Now I want to change the url if the user clicks on the button and reset the url if the user closes the div. I already now about the history mode. For example he clicks button 1, the url should change from example.com/product/1/ to example.com/product/1/video/1. And if he closes the div the opposite way. I also want, if the user goes directly to video/1, that the page should load and automatically fire the ajax request and load the desired content.

How can I achieve this?

My thoughs for the laravel routing: Set up a route for products/{product_id}/{video/video_id?}. But the video shouldn't load on that particular request. I don't think it's possible to set the last part as optional as I did here, is it?

For the vue part I really don't hav ea clue how to achieve the desired behaviour. I heard about vue-router, but I never worked with it before and I heard it's just for SPA's?

8th December, 2017

ronon left a reply on JS Generated Url Not Working. Same Url Typed In Manually Works. • 9 months ago

Weird that part was working O.o The perPage part wasn't working. I rewrote the numbers and now it's working. Weird bug.

ronon started a new conversation JS Generated Url Not Working. Same Url Typed In Manually Works. • 9 months ago

I'm trying to implement a perPage functionality to a site. I have different dropdown boxes where the user can choose the order, perPage and some other values. If he clicks submit i generate an url with the given values and redirect the user with location.href (Form not really possible since i'm using https://vuetifyjs.com/releases/0.15/ ).

If i redirect the user now to a js generated url like: http://127.0.0.1:8000/products?perPage=54&orderBy=asc&order=title i receive and 302 redirect.

But if I enter the same url manually in the address bar: http://127.0.0.1:8000/products?order=asc&orderBy=title&perPage=54 it works.

dd() output called with js:

array:3 [▼
  "perPage" => "54"
  "orderBy" => "asc"
  "order" => "title"
]

dd() output entered manually in address bar:

array:3 [▼
  "order" => "asc"
  "orderBy" => "title"
  "perPage" => "54"
]

rule:

return [
            'perPage' => 'nullable|numeric',
            'orderBy' => ['nullable', Rule::in($this->orderBy)],
            'order' => ['nullable', Rule::in($this->order)]
        ];

I also tried to remove/change the perPage key, but with no effect.

Why the heck is the js generated url not working but the manually one does?

I'm getting crazy. It looks exactly the same and it's working if entered manually :(

18th November, 2017

ronon left a reply on Try Catch Without Throwing A Server Error? Execute The Rest Of The Script If An Execption Is Thrown • 10 months ago

Seems like it was a namespacing issue as mentioned from @lostdreamer_nl . Changed it to \Exception and it seems to work now. Thanks

16th November, 2017

ronon left a reply on Try Catch Without Throwing A Server Error? Execute The Rest Of The Script If An Execption Is Thrown • 10 months ago

I have several unique database conditions. I try to precheck them, but sometimes it just fails. So I definitly need to handle it with a try/catch block.

ronon started a new conversation Try Catch Without Throwing A Server Error? Execute The Rest Of The Script If An Execption Is Thrown • 10 months ago

Hi,

I'm writing an api and some of the code could fail if an db entry already exists. Is there a away to surround this with a try catch block and execute the rest of the code which does not append on it?

Sth like

try{
  $model = Model::create($data);
 
  $res['created'][] = ['id' => $model->id];

} catch(Exception $e){
    
    $res["error"] = "Couldn't create entry: " .$e->toString();
}

// Execute more code, return json response

Curerntly the problem is, that it throws an 500 server error but that is in this case counterproductive.

ronon left a reply on Subdomain Shows Content Of Main, Should Display Error Page? • 10 months ago

I created a own subdomain for the api. It's called like api.example.com/api/whatever. I do it to be able to have a own php-fpm pool for the subdomain. Using nginx if that helps.

15th November, 2017

ronon started a new conversation Subdomain Shows Content Of Main, Should Display Error Page? • 10 months ago

Hi,

i'm developing an api for a laravel based site and i'm confused with the routing.

In my RouteServiceProvider I added:

  protected function mapApiRoutes()
    {
        Route::prefix('v1')
             ->middleware(['api', 'auth:api'])
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

Then in the api.php


Route::domain('{api}.'.config('app.url'))->group(function () {
    Route::get('/status', function () {

        return response()->json(['online']);
    });


    // create post
    Route::post('/post', 'Api\[email protected]');

});

What I don't understand is, if I go to api.example.com I get the content of the main page. Shouldn't there occur a 404 error? It isn't any route defined what would explain this behaviour.

Or is it because of ´´´php Route::get('/', '[email protected]')->name('home'); ´´´ in my web.php?

If so how to disable this behaviour and show empty pages or an error page for anything the user tries to browse?

11th November, 2017

ronon started a new conversation Subdomain Own Log File? • 10 months ago

Hi,

i have mutliple subdomains on my laravel project. Now i want to have a seperate logfile for each subdomain. Is this even possible?

6th November, 2017

ronon left a reply on Get Url And Title/name From A Polymorphic Relation In Blade • 10 months ago

@thethan I totally missed/forgot that. That will solve my problem.

I'm not quite sure, but i think I can remember myself that in the laracasts tutorial was an annotation how to handle polymorphic relation in blade. I can't remember in which episode it was, but i'm quite sure it was there. Does anyone know which episode I mean or rather which blade function he referred to?

ronon left a reply on Get Url And Title/name From A Polymorphic Relation In Blade • 10 months ago

I can get the body without a problem, but I need to get the url from the relation, like:

@foreach($comments as $comment)

    <tr>
        <td>{{ $comment->body }}</td>
        <td>{{ route('post.show', ['post' => $comment->post->id]) }}</td> OR
    <td>{{ route('video.show', ['video' => $comment->video->id]) }}</td>
    </tr>
@endforeach 

How to create a specific switch?

Edit Your Profile
Update

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