Cinek

Experience

24,780

42 Best Reply Awards

  • Member Since 1 Year Ago
  • 1 Lesson Completed
  • 0 Favorites

18th September, 2018

Cinek left a reply on I Wanna Get All Articles With Votes • 4 days ago

Try this

 $articles = Article::with('user', 'categorie', 'comments', 'votes')
            ->withCount('votes', 'cryptoVotes')
            ->where('created_at', '<=', Carbon::now()->subHour(1))
            ->has('crypto_votes_count', '>', 5)
            ->paginate(20);

16th September, 2018

Cinek started a new conversation Chat's Database Structure • 6 days ago

Hello, I have one problem with designing database structure for my app. I have 3 models: Events, groups and users. Relations: Events - Users - many to many Groups - Users - many to many

There will be available one chat withing group and one inside event. Additonally in the near future I am going to implement chats between two or more users.

i'm a bit confused what is the best way to design it. I created Chat model and many to many relation between chat and users.

1 idea: The members of group and event chats will be stored in respectively event_users and group_users tables. Only chats between users will be stored in chat_users.

Second idea: chat_users will be synchronized with event_users and group_users tables. The advantage of this way is that I will have simple separated logic to manage chats and there will be not many complicated queries to DB.

Thanks for any feedback or maybe other ideas

28th August, 2018

Cinek left a reply on Many To Many In RestFUL API • 3 weeks ago

Do you mean that user_groups should be separate resource in API and to store invitations in another table? Something like this?

  • /users - get list of users
  • users/{userId} - get user details

GET user_groups all user_groups GET user_groups/{id} details POST user_groups add user to group PUT user_groups update user role in group

GET group_invitations group_invitation GET group_invitations/{id} detail of invitation POST group_invitations add invitation DELETE group_invitations delete invitation

  1. Now can how to get all of groups of specific user? /users/{userId}/groups or /user_groups?user_id={id}

Cinek left a reply on Many To Many In RestFUL API • 3 weeks ago

Do you mean that user_groups should be separate resource in API and to store invitations in another table? Something like this? GET users get list of users GET users/{userId} get user details

GET user_groups all user_groups GET user_groups/{id} details POST user_groups add user to group PUT user_groups update user role in group

GET group_invitations group_invitation GET group_invitations/{id} detail of invitation POST group_invitations add invitation DELETE group_invitations delete invitation

  1. Now can how to get all of groups of specific user? /users/{userId}/groups or /user_groups?user_id={id}

27th August, 2018

Cinek left a reply on Is There A Reason Why Dd/var_dump/die Event Exit Doesn't Work Anymore • 3 weeks ago

What does it mean "not working"?

Cinek left a reply on Global Partial Routes On Resources • 3 weeks ago

According to the sources:

 public function resources(array $resources)
    {
        foreach ($resources as $name => $controller) {
            $this->resource($name, $controller);
        }
    }

I think you have to define your resource routes separatly.

Cinek left a reply on Accessing A Page If You're Within A Specific IP Address Range? • 3 weeks ago

public function handle($request, Closure $next)
    {
        $startIp = ip2long('192.168.1.1');
        $endIp = ip2long('192.168.1.100');
    $requestIp = ip2long($request->ip());
        if($searchedIp >= $startIp && $searchedIp <= $endIp){
            abort(404);
        }
        return $next($request);

Cinek started a new conversation Many To Many In RestFUL API • 3 weeks ago

I have 2 tables: user:

  • id
  • name group:
  • id
  • name user_groups:
  • id
  • user_id
  • group_id
  • status
  • role

In the user_groups table there can be only one entry with given user_id and group_id. When user is invited to group there should be created user_groups entry with status = 0. When user accepts invitation status should change to 1. My question is how to design restful routes to this situation. How to add/edit entries in user_groups table?

26th August, 2018

Cinek left a reply on Method Update Does Not Exist (Event Destroy Method) • 3 weeks ago

update method will not work on collection of models, only on single model or query builder.

You can do this:

 $participants = $event->participants()->where('event_id', $event->id)->update([ 
                    'status_id' => 5, 
                ]);

23rd August, 2018

Cinek left a reply on How Can I Update Just The Changes In Model? • 4 weeks ago

$userData = $request->only('first_name','last_name','username');
$user->update($userData);

Cinek started a new conversation RequestHandled Event • 4 weeks ago

I'm using Lumen 5.6 and I write package which will add some extra values to JSON responses. In laravel there is a Illuminate\Foundation\Http\Events\RequestHandled event but I can't find it in Lumen. Is there any similar event in Lumen? Temporarily I created my own event and I dispatch it in middleware but I don't think so it is a good solution.

7th August, 2018

Cinek left a reply on Get OnlyTrashed() Does Not Exist In Query Builder • 1 month ago

What version of laravel do you use?

2nd August, 2018

Cinek left a reply on Laravel 5.6 Realtime Notification • 1 month ago

Have a look at broadcasting https://laravel.com/docs/5.6/broadcasting

Cinek left a reply on Relations In Model Events • 1 month ago

Thanks for response :) It's only my thoughts. I'm learning how laravel works. I thought that an object is passed to event listener with all it properties but it's not. I'd like to find out why this is happening, not find a workarround of this situation.

Cinek left a reply on Laravel Updating Relationship Column In WhereHas • 1 month ago

$unused = Sale::whereHas('salesdetails',function($query) {
             $query->where('product_id', '<=', 24)->where('switch', 1);
        })->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now)

This query returns a Sale models so you perform update switch on sales table. You should start your query from SalesDetails model, something like this:

SalesDetail::whereHas('sale', function ($query) use ($now) {
            $query->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now);
        })->where('product_id', '<=', 24)->where('switch', 1)
            ->update(['switch' => 0]);

1st August, 2018

Cinek left a reply on Relations In Model Events • 1 month ago

asdf

Cinek left a reply on Database Wont Update • 1 month ago

Can you see what the table timeouts and Timeout model looks like?

Cinek left a reply on Can Someone Show Me The Correct Way To Fix This Relationship • 1 month ago

Your User <=> Skill relation seems to be "many to many" relation. https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

User.php

public function skills(){
        return $this->belongsToMany('App\Skill');
}

Skill.php

public function users(){
        return $this->belongsToMany('App\User');
}

and you don't have UserSkill model.

29th July, 2018

Cinek left a reply on Laravel Route Conflict • 1 month ago

Laravel takes the first matching route. Placing search route above show route file should do the job.

26th July, 2018

Cinek left a reply on Raw Sql To Eloquent • 1 month ago

By the way it seems to me that the relation User-> Favorite -> Post should be manyToMany with favorite table as a pivot

Cinek left a reply on Raw Sql To Eloquent • 1 month ago

The fastest way to find all post favoured by logged user:

$post = Post::whereHas('favourite', function($query){
            $query->where('user_id', Auth::id());
        })->get();

This code will generate query select * from `posts` where exists (select * from `favourites` where `posts`.`id` = `favourites`.`post_id` and `user_id` = '1')

25th July, 2018

Cinek left a reply on Why In The Payment_c Column Is Stored 0 And Not 1? • 1 month ago

What type is Column payment_mb and payment_c?

Cinek left a reply on Get Districts Through Councils Relationship • 1 month ago

Sorry, my mistake, I missunderstood.

public function council(){
        return $this->belongsTo(Council::class, 'county_id');
    }

and then

$jobs = Job::with('council.district')->get();
foreach($jobs as $job) {
echo $job->council->district->name;
}

Cinek left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax • 1 month ago

@baguus you can do it with withDefault method introduced in laravel 5.5

public function mainDistributorUsers()
    {
        return $this->hasOne(User::class, 'id', 'main_distributor_id')->withDefault([
            'username' => 'Default username' //or place another name with main_distributor_id is null
        ]);
    }

and if your company will have null in main_distributor_id then $company->mainDistributorUsers->username will show "Default username".

Cinek left a reply on Get Districts Through Councils Relationship • 1 month ago

Same as in County model.

Cinek left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax • 1 month ago

<td>{{ $company->mainDistributorUsers->username }}</td>

seems to be correct. You are sure that all your companies have a main_distributor_id field filled in? If one of the company will have null in main_distributor_id it will thrown exception.

Cinek left a reply on Interesting Question With Model In Laravel • 1 month ago

You can set database connection on the fly:

$model1 = (new Model)->setConnection('mysql')->first();

or in static context

$model2 = Model::on('mysql')->first();

24th July, 2018

Cinek left a reply on Going Down Multiple Relationship Layers • 1 month ago

$page = Page::with('boxes.item')->where('id',$id)->first();

18th July, 2018

Cinek left a reply on Ordering With Eloquent • 2 months ago

Simply use orderBy function twice:

->orderBy('field1','asc')->orderBy('field2','desc')

It will generate order by field1 asc, field2 desc

13th July, 2018

Cinek left a reply on Retrieving BelongsTo Relationship • 2 months ago

You should use relation as an attribute

$assignment->category

(without brackets).

12th July, 2018

Cinek left a reply on Undefined Variable • 2 months ago

Why have you

$message->string('message');

not

$table->string('message');

?

10th July, 2018

Cinek left a reply on [L5.*] Pagination: Change URL Query Name "page" Globally • 2 months ago

Third parameter of paginate method do this

->paginate($limit,['*'],'seite')

Cinek left a reply on How To Setup Custom If Statement • 2 months ago

Blade::if('isadmin', function () {
            return Auth::guard('admin')->check();
        });

and in blade

@isadmin
I'm admin
@else
I'm not admin
@endelseadmin

Blade::if('admin', function () { $role = Auth::guard('admin')->user()->role; return in_array($role, func_get_args()); });

in blade

@admin('manager', 'owner', 'administrator')

9th July, 2018

Cinek left a reply on Track Changes In A Model And Store In Other Table • 2 months ago

->map(function ($value, $field) use ($func) {
                return call_user_func_array($func, [$value, $field]);
             })

change to

->map(function ($value, $field) use ($func,$model) {
                return call_user_func_array($func, [$value, $field,$model]);
             })

and

protected function getHistoryBody($value, $field)
    {
        return [
            'body' => "Updated {$field} to ${value}",
        ];
    }

to

protected function getHistoryBody($value, $field, $model)
    {
$oldValue = $model->getOriginal($field);
        return [
            'body' => "{$field} Updated From {$oldValue} to {$value}",
        ];
    }

8th July, 2018

Cinek left a reply on Variables Refer To The Same Value • 2 months ago

You have to change = to == :)

By the way you also have mixed up descriptionde and descriptionen

Cinek left a reply on Laravel 5.6 Pass String To Blade Component Is Object ? • 2 months ago

No, only if you inject data into component via @slot directive. For example, if you pass a variable from controller you don't need to use toHtml method.

7th July, 2018

Cinek left a reply on Maintenance Mode Events? • 2 months ago

I don't know if that event is available but you can override it in service provider.

AppServiceProvider

$this->app->extend('command.down', function () {
            return new MyCustomDownCommand();
        });
use Illuminate\Foundation\Console\DownCommand;

class MyCustomDownCommand extends DownCommand
{
    public function handle()
    {
        $this->comment('my php artisan down handler');
        parent::handle();
    }
}

and similarly you can do it with UpCommand

Cinek left a reply on Laravel On Centos7/Apache • 2 months ago

I assume these permissions are from before you setting sudo chmod -R 777 /var/. Is the/var/www/html/checkers/storage/framework/views/``` directory exists?

6th July, 2018

Cinek left a reply on When I Want Download Excel? • 2 months ago

If you do not paste any line of code we have no chance to help you.

5th July, 2018

Cinek left a reply on Edit API Response • 2 months ago

Why do want to have property quiz_name twice in second JSON ?

Cinek left a reply on Trying To Set Up Download For Pdf In My Db • 2 months ago

Show code how do you upload your pdf

Cinek left a reply on Condition Based Iteration Using For Loop In JavaScript • 2 months ago

If you want to go into next iteration you can use continue; statement:

if(audio.ended == true) {
            continue;
        }

Cinek left a reply on When I Want Download Excel? • 2 months ago

Show your line 62 in Reports.php

Cinek left a reply on Modify Collection Values Based On A Condition • 2 months ago

for example:

$collection = collect([1,2,3]);
        $newCollection = $collection->map(function ($item, $key) {
            switch($item){
                case 1:
                    return 'YES';
                case 2:
                    return 'NO';
                case 3:
                    return 'MAYBE';
                default:
                    return '';
            }
        });

3rd July, 2018

Cinek left a reply on Passing Variable From Middleware To Blade • 2 months ago

Why do you want to pass variable to view in middleware? Better choice to passing variable to multiple views is to use View Composer

View::composer('*', function ($view) {
        $variable = 'value';
        $view->with('myvariable', $variable );
    });

Now you can use {{ $myvariable}} in all of your views.

Cinek left a reply on Querybuilder Pass Column To Nested Query • 2 months ago

$events = Event::with('comments')->whereHas('comments',function ($query) {
            $query->whereColumn('comments.created_at','<','events.start');
        })->get();

whereColumn is function to compare columns in query.

Cinek left a reply on Using Sql Function In Laravel Eloquent • 2 months ago

You can get te value returned by your function with this code

        $functionData = DB::select("select myfunction() as value");
        $category ->type = array_shift($functionData)->value;

If you want it to be done automatically after inserting category to DB place this code in laravel model observer:

class CategoryObserver
{
    public function created(Category $category)
    {
        $functionData = DB::select("select myfunction() as value");
        $category ->type = array_shift($functionData)->value;
        $user->save();
    }

28th June, 2018

Cinek left a reply on Cannot Access My API Routes After Deploying My Server • 2 months ago

does the root route works?

Edit Your Profile
Update

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