slickness

slickness

Member Since 1 Year Ago

Experience Points 4,650
Experience Level 1

350 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 11
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

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

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

12 May
1 week ago

slickness started a new conversation Database Query

I have just quereme small quereme at a database query. How can I already select the posts in the database query below for specific values ​​in the controller?

$user->mentioned_lead_user()->with('posts', 'users')->latest()->get();
11 May
1 week ago

slickness started a new conversation Preg_match_all With More Than One Value

I use preg_mtach_all to find the mention of usernames and stored tags in the 'body' and to replace them accordingly so that the corresponding texts have the correct link. How can I find the usernames and tags in several fields, for example: body, title and article, and output them as before?

public function getBodyAttribute($value) {
        $value = $this->replaceUserNames($value);
        $value = $this->replaceTags($value);
        return $value;
    }

    protected function replaceUserNames($body) {

        preg_match_all('/@(\w+)/', $body, $users);
        if (!isSet($users[1])) {
            return $body;
        }

        $userList = User::whereIn('username', $users[1])->get();
        foreach ($userList->unique() as $user) {
            $replace = $user->username;
            $replacename = $user->username;
            if ($user->isFollowed(Auth::user())) {
                $replace = $user->username;
                $replacename = $user->username;
            } elseif ($user->profile->privacy == 3 && $user->id !== auth()->id()) {
                $replace = $user->id;
                $replacename = $user->id;
            }
            $body = str_replace('@' . $user->username, '<a href="/profile/' . $replace . '">@' . $replacename . '</a>', $body);
        }
        return $body;
    }

    protected function replaceTags($body) {
        preg_match_all('/#(\w+)/', $body, $tags);
        if (!isSet($tags[1])) {
            return $body;
        }
        $tagList = Collect($tags[1]);
        foreach ($tagList->unique() as $tag) {
            $body = str_replace('#' . $tag, '<a href="/tags/in/media/' . $tag . '">#' . $tag . '</a>', $body);
        }
        return $body;
    }
10 Jan
4 months ago

slickness started a new conversation Big Problem With Jscroll.js

I integrated jscroll into my project and it works great too. The data are loaded and displayed when scrolling.

The problem is, when loading new data is displayed, no longer works with the new data javascript code.

If I manually reload the Javascript code, the javascript code will work on the new data. For the old uncharged data, each function is executed twice.

However, when I manually call the second page via paginator, the whole code works.

I have been looking for a solution for several days now, unfortunately I can not find one. Even in the console, no error or the like is displayed.

I hope that I will find help with you.

02 Jan
4 months ago

slickness started a new conversation Seed Data From Github Package - Igaster/laravel_cities

I have the following package of github loaded and installed exactly as described in the instructions: https://github.com/igaster/laravel_cities

It all funtions everything how it should work. The problem is that not all cities are transferred from the .txt file to the database, but only the cities with a certain size. This is the seed file:

 class seedGeoFile extends Command
{
    protected $signature = 'geo:seed {country?} {--append}';
    protected $description = 'Load + Parse + Save to DB a geodata file.';
    private $pdo;
    private $driver;
    public function __construct() {
        parent::__construct();

        $connection = config('database.default');
        $this->driver = strtolower(config("database.connections.{$connection}.driver"));

        $this->pdo = \DB::connection()->getPdo(\PDO::FETCH_ASSOC);
        if (!\Schema::hasTable('geo'))
            return;
        $this->geoItems = new geoCollection();
    }
    public function sql($sql){
        $result = $this->pdo->query($sql);
        if($result === false)
            throw new Exception("Error in SQL : '$sql'\n".PDO::errorInfo(), 1);

        return $result->fetch();
    }    
    public function buildDbTree($item, $count = 1, $depth = 0){
        $item->left=$count++;
        $item->depth=$depth;
        foreach ($item->getChildren() as $child) {
            $count = $this->buildDbTree($child, $count, $depth+1);
        }
        $item->right=$count++;
        return $count;
    }

    public function printTree($item){
        $levelStr= str_repeat('--', $item->depth);
        $this->info(sprintf("%s %s [%d,%d]", $levelStr, $item->getName(),$item->left,$item->right));
        foreach ($item->getChildren() as $child)
            $this->printTree($child);
    }
    public function handle() {
        $start = microtime(true);
        $fileName = $this->argument('country') ? strtoupper($this->argument('country')) : 'allCountries';
        $fileName = storage_path("geo/{$fileName}.txt");
        $append =  $this->option('append');
        // Read Raw file
        $this->info("Reading File '$fileName'");
        $filesize = filesize($fileName);
        $handle = fopen($fileName, 'r');
        $count = 0;
        $progressBar = new \Symfony\Component\Console\Helper\ProgressBar($this->output, 100);
        while (($line = fgets($handle)) !== false) {
            // ignore empty lines and comments
            if ( ! $line or $line === '' or strpos($line, '#') === 0) continue;
            // Convert TAB sepereted line to array
            $line = explode("\t", $line);
            // Check for errors
            if(count($line)!== 19) dd($line[0],$line[2]);
            switch ($line[7]) {
                case 'PCLI':    // Country
                case 'PPLC':    // Capital
                case 'ADM1':
                case 'ADM2':
                case 'ADM3':
                    $this->geoItems->add(new geoItem($line, $this->geoItems));
                    $count++;
                    break;
            }
            $progress = ftell($handle)/$filesize*100;
            $progressBar->setProgress($progress);
        }
        $progressBar->finish();
        $this->info(" Finished Reading File. $count items loaded</info>");
        // Read hierarchy
        $fileName = storage_path('geo/hierarchy.txt');
        $this->info("Opening File '$fileName'</info>");
        $handle = fopen($fileName, 'r');
        $filesize = filesize($fileName);
        $count = 0;
        $progressBar = new \Symfony\Component\Console\Helper\ProgressBar($this->output, 100);
        while (($line = fgetcsv($handle, 0, "\t")) !== false) {
            $parent = $item=$this->geoItems->findGeoId($line[0]);
            $child  = $item=$this->geoItems->findGeoId($line[1]);
            if( $parent !== null && $child !== null){
                $parent->addChild($line[1]);
                $child->setParent($line[0]);
                $count++;
            }
            $progress = ftell($handle)/$filesize*100;
            $progressBar->setProgress($progress);
        }
        $this->info(" Hierarcy building completed. $count items loaded</info>");
        // Build Tree
        $count = 0; $countOrphan = 0;
        $sql = 'SELECT MAX("right") as maxRight FROM geo';
        $result = $this->sql($sql);
        $maxBoundary = isset($result['maxRight']) ?  $result['maxRight']+1 : 0;
        foreach ($this->geoItems->items as $item) {
            if($item->parentId === null){

                if($item->data[7] !== 'PCLI'){
                    // $this->info("- Skiping Orphan {$item->data[2]} #{$item->data[0]}");
                    $countOrphan++;
                    continue;
                }
                $count++;
                $this->info("+ Building Tree for Country: {$item->data[2]} #{$item->data[0]}");
                $maxBoundary=$this->buildDbTree($item,$maxBoundary,0);
                // $this->printTree($item,$output);
            }
        }
        $this->info("Finished: {$count} Countries imported.  $countOrphan orphan items skiped</info>");
        // Empty Table
        if (!$append){
            $this->info("Truncating 'geo' table...");
            \DB::table('geo')->truncate();
        }
        // Store Tree in DB
        $this->info("Writing in Database</info>");

        if ($this->driver == 'mysql') {
            $stmt = $this->pdo->prepare("INSERT INTO geo (`id`, `parent_id`, `left`, `right`, `depth`, `name`, `alternames`, `country`, `level`, `population`, `lat`, `long`) VALUES (:id, :parent_id, :left, :right, :depth, :name, :alternames, :country, :level, :population, :lat, :long)");
        } else {
            $stmt = $this->pdo->prepare("INSERT INTO geo (\"id\", \"parent_id\", \"left\", \"right\", \"depth\", \"name\", \"alternames\", \"country\", \"level\", \"population\", \"lat\", \"long\") VALUES (:id, :parent_id, :left, :right, :depth, :name, :alternames, :country, :level, :population, :lat, :long)");
        }
        $count = 0;
        $totalCount = count($this->geoItems->items);
        $progressBar = new \Symfony\Component\Console\Helper\ProgressBar($this->output, 100);
        foreach ($this->geoItems->items as $item) {
            if ( $stmt->execute([
                ':id'           => $item->getId(),
                ':parent_id'    => $item->parentId,
                ':left'         => $item->left,
                ':right'        => $item->right,
                ':depth'        => $item->depth,
                ':name'         => substr($item->data[2],0,40),
                ':alternames'   => $item->data[3],
                ':country'      => $item->data[8],
                ':level'        => $item->data[7],
                ':population'   => $item->data[14],
                ':lat'          => $item->data[4],
                ':long'         => $item->data[5]
            ]) === false){
                throw new Exception("Error in SQL : '$sql'\n".PDO::errorInfo(), 1);
            }
            $progress = $count++/$totalCount*100;
            $progressBar->setProgress($progress);
        }
        $progressBar->finish();
        $this->info(" Done</info>");
        $time_elapsed_secs = microtime(true) - $start;
        $this->info("Timing: $time_elapsed_secs sec</info>");
    }
}

Can someone help me how I can save all cities from the .txt file to the database? Or can someone recognize where in the code the certain cities are selected?

18 Nov
6 months ago

slickness started a new conversation Laravel Helper

The user has the possibility to archive his mail that he is no longer visible to anyone. If the post has been archived, it gets a 1 in the table posts in the column archived, if it is not archived, it gets a 0.

how can I now check the post with a hilffunktion that he is archived or not? If I use my code, it works only if garkein post was archived.

Model:

public function isArchivededBy(User $user)
    {
        return $user->posts()
            ->where('archived', 1)
            ->exists();
    }

View:

 @if ($post->isArchivededBy(Auth::user()))
                                                            <form class="m-0" id="destroyarchived{{$post->id}}" action="{{ route('user.archive.post.destroy', $post->id) }}" method="post">
                                                                {{ csrf_field() }}
                                                                {{ method_field('DELETE') }}
                                                                <a class="p-2" href="#" onclick="document.getElementById('destroyarchived{{$post->id}}').submit()">
                                                                    <i class="glyphicon glyphicon-ok-circle fa-lg"></i>Veröffentlichen
                                                                </a>
                                                            </form>
                                                        @else
                                                            <form class="m-0" id="addarchived{{$post->id}}" action="{{ route('user.archive.post', $post->id) }}" method="post">
                                                                {{ csrf_field() }}
                                                                <a class="p-2" href="#" onclick="document.getElementById('addarchived{{$post->id}}').submit()">
                                                                    <i class="glyphicon glyphicon-remove-circle fa-lg"></i>Verstecken
                                                                </a>
                                                            </form>
                                                        @endif
23 Oct
7 months ago

slickness left a reply on Use Function From Model In Notifications

@ I have to agree with you. It is better if I write the displylogic in the models. Thanks for the note :)

But with this code i get the follow error:

Call to a member function displayAuthorName() on array 

I would like to give you a better insight, maybe you can then help me to find a solution.

database

Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

save the notify:

//store notify for user in database
        $postn = Post::find($request->post_id);

        if($postn->user_id != Auth::id()) {
            User::find($postn->user->id)->notify(new NotifyComment($comment));
        }

Example entry in the database:

id:
type:
notifiable_id:
notofiable_type:
data: {"comment":{"body":"testcomment","user_id":1,"post_id":9,"privacy":3,"updated_at":"2018-10-16 19:02:31","created_at":"2018-10-16 19:02:31","id":74,"formatted_time":"1 second ago"},"user":{"id":1,"name":"name","team_id":1,"invited_from_id":null,"username":"testuser","email":"[email protected]","phone":null,"avatar":"/1/avatar/1537189269.jpg","slug":"testuser","birthday":"1980-01-30 00:00:00","gender":1,"created_at":"2018-09-16 19:20:16","updated_at":"2018-09-17 13:01:09","active":1,"activation_token":null},"post":{"id":9,"body":"testpost","titel":null,"articleText":null,"image":null,"image_thumbnail":null,"type":1,"status":1,"privacy":1,"user_id":2,"created_at":"2018-10-15 15:43:50","updated_at":"2018-10-15 15:43:50"},"profile":{"id":1,"user_id":1,"about":null,"webpage":null,"cover":"public/1/cover/jClNRrMhbfdQge205j0SucQSG6ZPGMkvHmPFvwVC.png","thumbnail":"/1/cover/thumb/1537353515thumbnail.png","privacy":3,"created_at":"2018-09-16 19:20:16","updated_at":"2018-09-19 10:38:35"}}
22 Oct
7 months ago

slickness left a reply on Use Function From Model In Notifications

@Roni

You're right, it's certainly not easy to help me with so little information. Thank you for your patience and your good help. I hope, we find a solution. The repo is not public. I will post the code here. This is my current code:

View:

Header

<li class="quick-cart" id="notification-button">
          <a class="m-0" href="#">
            @if (auth()->user()->unreadNotifications->count())<span class="badge badge-green btn-sm badge-corner mt-10">{{auth()->user()->unreadNotifications->count()}}</span>@endif
            <i class="fa fa-globe fs-25" @if(auth()->user()->unreadNotifications->count()) style="color:#9c3;" @else style="color:#245580;"  @endif></i>
          </a>

          <div class="quick-cart-box">
            <h4><i class="fa fa-globe"></i>  {{__('header.2')}}</h4>
            <div class="quick-cart-wrapper">
              @if (auth()->user()->notifications->count() == 0)
                <div class="text-center text-black mt-15">
                  <i class="glyphicon glyphicon-warning-sign fa-2x"></i>
                  <h5 class="fs-11 mb-15 mt-5">Du hast noch keine Benachrichtigungen erhalten.</h5>
                </div>
              @else
                <div class="infinite-scroll">
                  @foreach(auth()->user()->notifications()->paginate(10) as $notification)
                    @include('elements.notifications.'.snake_case(class_basename($notification->type)))
                  @endforeach
                  {{auth()->user()->notifications()->paginate(10)->links()}}
                </div>
              @endif
            </div>
          </div>
        </li>

notify_comment.blade.php

<a class="@if($notification->read_at)@else unread-notification @endif min-height-60" href="#">
    <img class="rounded mt-5" src="@if(Auth::id() == $notification->data['user']['id'] OR $notification->data['profile']['privacy'] == 1 OR $notification->data['profile']['privacy'] == 2) {{ Storage::url($notification->data['user']['avatar']) }} @else {{Storage::url($user->AnonymAvatar) }} @endif" width="45" height="45" alt="" />
    <small class="float-right" style="color:#666">{{$notification->created_at->diffForHumans()}}</small>
    <h5 class="fs-11 text-black mt-10 mb-0"><b>@if( Auth::id() == $notification->data['user']['id'] OR $notification->data['profile']['privacy'] == 1 OR $notification->data['profile']['privacy'] == 2){{$notification->data['user']['username']}}@else AC @endif</b> hat dein Post kommentiert: <b>{!! $notification->data['comment']['body'] !!}</b></h5>
</a>
```
NotifyComment.php
```

class NotifyComment extends Notification
{
    use Queueable;

    protected $comment;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($comment)
    {
        $this->comment = $comment;
        $this->author = $comment->user;
    }

    public function displayAuthorName(){


        if( auth()->id() == $this->comment->user->id ||
            in_array($this->comment->user->privacy, 1)|| in_array($this->comment->user->privacy, 2) ||
            $this->comment->user->isFollowed()) {

            return $this->comment->user->username;

        }
        return 'AC';

    }
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];

    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'comment' => $this->comment,
            'user' => User::find($this->comment->user_id),
            'post' => Post::find($this->comment->post_id),
            'profile' => Profile::find($this->comment->user_id),
        ];

    }
}
```

In the header view I load the appropriate view for the notification type. For example, if it is a comment notification, then notify_comment.blade.php is loaded. If it is a comment review, it will load notify_comment_activity.blade.php.
18 Oct
7 months ago

slickness left a reply on Use Function From Model In Notifications

@roni thanks for your help. Unfortunately it does not work. I have added the helper function to my NotifyComment. But I get the following error message:

Call to undefined method Illuminate\Notifications\DatabaseNotification::displayAuthorName() 
17 Oct
7 months ago

slickness started a new conversation Users Activity

I want to create an activity stream. In the stream, the user can see what the user is doing which he follows.

I have the following database for this:

id
user_id
type   //follow, likes,...
activityable_id
activityable_type

How can I display the data in the view if I have different types?

How can I summarize the same activities and load the data from them:

For example: Username rated 5 posts. (here I would like to present the pictures of the posts)

slickness left a reply on Use Function From Model In Notifications

@Roni thanks for your help. Thank you for your help. But how can I integrate this into my if statement?

@if( Auth::id() == $notification->data['user']['id'] OR $notification->data['profile']['privacy'] == 1 OR $notification->data['profile']['privacy'] == 2 OR $notification->data['user']->isFollowed(Auth::id()) ){{$notification->data['user']['username']}}@else AC @endif ```
16 Oct
7 months ago

slickness started a new conversation Use Function From Model In Notifications

How can I use functions of the model in the notifications of laravel?

i want to use this function:

     public function isFollowed()
        {
            return $this->followers()
                ->where('follower_id', auth()->id())->exists();
        }

i get the follow error: Call to a member function isFollowed() on array This is my current code:

    <a class="@if($notification->read_at)@else unread-notification @endif min-height-60" href="#">
            <img class="rounded mt-5" src="{{ Storage::url( $notification->data['user']['avatar'] ) }}" width="45" height="45" alt="" />
            <small class="float-right" style="color:#666">{{$notification->created_at->diffForHumans()}}</small>
            <h5 class="fs-11 text-black mt-10 mb-0"><b>@if( Auth::id() == $notification->data['user']['id'] OR $notification->data['profile']['privacy'] == 1 OR $notification->data['profile']['privacy'] == 2 OR $notification->data['user']->isFollowed(Auth::id()) ){{$notification->data['user']['username']}}@else AC @endif</b> hat dein Post kommentiert: <b>{!! $notification->data['comment']['body'] !!}</b></h5>
        </a>

if i use

    $notification->data['user']['id']->isFollowed(Auth::id())

Then i get the follow error:

    Call to a member function isFollowed() on integer
15 Oct
7 months ago

slickness started a new conversation Link Tagging Username To Profile

At the moment I link every word from the body of the post that follows a @ to a profile. The following code is in the post model. The problem is, it will also be linked if the profile does not exist.

How can I make sure that the profile exists and only then link to the profile?

And if the user has a privacy of 3, the profile should be linked to the ID and not to the username. But the Auth::user() can see his username.

09 Oct
7 months ago

slickness left a reply on Additional Data In Foreach

i found a solution:

public function index() 
{ 
 $user = Auth::user(); 
 $groups = $user->groups()->latest()->with('tags')->paginate(20); 
 $ratio = null; 
 foreach($groups as $key => $group) 
 { 
  $tagIdArray = $group->tags->pluck('id')->all(); 
  $mostvotedarticle = Article::where('type', 4)->whereIn('privacy', [1, 3]) 
  ->whereHas('tags', function($query) use ($tagIdArray) { 
  $query->whereIn('tags.id', $tagIdArray); 
  }, '>=', count($tagIdArray)) 
  ->orderByVotes()->first(); 

 $articledown = Article::where('status', 1)->whereHas('tags', function($query) use 
 ($tagIdArray) { 
 $query->whereIn('tags.id', $tagIdArray); 
 }, '>=', count($tagIdArray))->downVotesAll()->count(); 

$articleup = Article::where('status', 1)->whereHas('tags', function($query) use 
($tagIdArray) { 
$query->whereIn('tags.id', $tagIdArray); 
}, '>=', count($tagIdArray))->upVotesAll()->count(); 


if($articleup + $articledown == 0) { 
$ratio = 0; 
} else { 
$ratio = ($articleup*100)/($articleup + $articledown); 
} 

$group->mostVote = $mostvotedarticle; 
$group->ratio = $ratio; 
 } 
  return view('groups', compact('groups')); 
}

slickness started a new conversation What Is The Best And Most Flexible Way To Store And Count User Points?

I would like to credit users for different promotions. For example, when writing an articel, rate an articel ...

I am looking for a flexible solution in which I can adjust the points for the different actions and the total score also changes.

If I save the points in a table, I can not change them afterwards. Like this:

$request->user()->points += 10;
    $request->user()->save();

How about the performence when I recalculate the points each time? like this:

$articlepoints = $user->articles->count();
&votepoints = $user->votes->count();
$totalpoints = $articlepoints*10+$votepoints*5; 

are there any other options?

01 Oct
7 months ago

slickness left a reply on Ajax Not Sending Data To Controller

Did you make the table fillable in your model?

exampel:

protected $fillable = [
        'user_id', 'post_id'
    ];

slickness left a reply on Additional Data In Foreach

does anyone know a solution?

25 Sep
7 months ago

slickness left a reply on Additional Data In Foreach

@snapey

I have the functions in the model. I attached the functions to my first post.

slickness left a reply on Additional Data In Foreach

@Snapey

The foreach loop is only from the index function. Not from the show function.

slickness started a new conversation Additional Data In Foreach

In my show function in which you can watch every single group, I load all articles with the same tags. And the article with the most votes will be displayed separately at the top. In addition, I indicate the average rating of the items in this group. This is how my function looks like:


public function show($id)
    {
        $group = group::find($id);

            $tagIdArray = $group->tags->pluck('id')->all();

            $mostvotedarticle = Article::where('type', 4)->whereIn('privacy', [1, 3])
                ->whereHas('tags', function($query) use ($tagIdArray) {
                    $query->whereIn('tags.id', $tagIdArray);
                }, '>=', count($tagIdArray))
                ->orderByVotes()->first();

            $articledown = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
                $query->whereIn('tags.id', $tagIdArray);
            }, '>=', count($tagIdArray))->downVotesAll()->count();

            $articleup = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
                $query->whereIn('tags.id', $tagIdArray);
            }, '>=', count($tagIdArray))->upVotesAll()->count();

            $ratio = null;

            if($articleup + $articledown == 0) {
                $ratio = 0;
            } else {
                $ratio = ($articleup*100)/($articleup + $articledown);
            }

        return view('singlegroup',compact('groups','mostvotedarticle', 'ratio'));
    }

On a overview page, the individual groups are displayed with a foreach loop:

@foreach ($groups as $group)
        {{$group->name}}                      
        <img src="-----load mostvotedarticle that is in this group------" alt="" />
        <div class="progress-bar-primary" style="width:{{$ratio}}%;">
@endforeach 

How can I have the mostvotedarticle and group ratings displayed in the foreach loop?

This is my previous index function:

public function index()
    {
        $user = Auth::user();
        $groups = $user->groups()->latest()->with('tags')->paginate(20);

        return view('groups', compact('groups'));
    }

slickness left a reply on Sequence Code Does Not Work

If i use it like this, it works:

$recent_tags = Taggable::where('created_at', '>=', now()->subHours(48))
    ->pluck("tag_id")
    ->filter()
    ->all();

$cnts = array_count_values($recent_tags); // count the values
arsort($cnts);                            // sort them
$cnts = array_slice($cnts, 0, 3, true);   // take however many
$tagIdArray = array_keys($cnts);         // the winners

$article = Article::with('comments', 'tags')
      ->whereIn('privacy', [1, 2])
      ->where('status', 1)
      ->whereHas('tags', function($query) use ($tagIdArray) {
        $query->whereIn('id', $tagIdArray);
      }, '>=', count($tagIdArray))
      ->latest()
      ->paginate(15);
21 Sep
8 months ago

slickness left a reply on Sequence Code Does Not Work

@burlresearch

thx for your help, i tested you code. But i become the follow error message:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select `tags`.*, `taggables`.`taggable_id` as `pivot_taggable_id`, `taggables`.`tag_id` as `pivot_tag_id`, `taggables`.`created_at` as `pivot_created_at`, `taggables`.`updated_at` as `pivot_updated_at` from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` where `taggables`.`taggable_id` in (49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63) and `taggables`.`taggable_type` = App\Post and `id` in (17, 21, 18, 23))
20 Sep
8 months ago

slickness started a new conversation Sequence Code Does Not Work

The $trendtag code alone works, but if I want to load the posts, I will not get any posts.

if I dd($tagIdArray); Execute, I get the id's of the tags. But the followin code has no function. if I do not use $trendtags, or only like this, it works:

$trendtags = Taggable::take(3)
            ->with('tag')
            ->get();

But how can I find the most used tags in the last 48 Hours? Is there another way?

$trendtags = Taggable::whereDate('created_at', '>=', now()->subHours(48)) ->groupBy('tag_id') ->orderByRaw('count(tag_id) DESC') ->take(3) ->with('tag') ->get();

    $tagIdArray = $trendtags->pluck('id')->all();

$article = Article::with('comments', 'tags')
  ->whereIn('privacy', [1, 2])
  ->where('status', 1)
  ->whereHas('tags', function($query) use ($tagIdArray) {
    $query->whereIn('id', $tagIdArray);
  }, '>=', count($tagIdArray))
  ->latest()
  ->paginate(15);
16 Sep
8 months ago

slickness left a reply on Load Tags From Taggables

@Digitalized

Thats not my problem. I want to load the 4 most used tags in the last 4 hour with this code:

$topTags = Taggable::whereDate('created_at', '>=', now()->subHours(4))
    ->groupBy('tag_id')
    ->orderByRaw('count(tag_id) DESC'))
    ->take(4)
    ->get();

And in my view i want to display the name of the found tags with $topTags.

slickness left a reply on Load Tags From Taggables

@Cronix

Thank you, the query works. What relationship do I need between tab table and taggables?How can I access the tag name in the view?

Schema::create('tags', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
15 Sep
8 months ago

slickness started a new conversation Load Tags From Taggables

I would like to display the 4 most used tags of the last 4 hours. How can I display it?

Table:

 Schema::create('taggables', function (Blueprint $table) {
            $table->integer('tag_id');
            $table->integer('taggable_id');
            $table->string('taggable_type');
            $table->timestamps();
        });

slickness left a reply on Linking Articles With Groups

I can not use the code. I always get the following error message:

Property [tags] does not exist on this collection instance.

This is the code:

 $groups_a = $user->groups()->with('tags')->get();

        $group_tag_ids = $groups_a->tags->pluck('id')->all();

        $article_by_tags = Article::all()->filter(function ($m) use ($group_tag_ids) {
            return $m->tags->pluck('id')->all() == $group_tag_ids;
        });
        $mostvotedarticle = $article_by_tags->where('type', 4)->whereIn('privacy', [1, 3])->orderByVotes()->first();
10 Sep
8 months ago

slickness left a reply on Linking Articles With Groups

@burlresearch I do not want to show all articles that have any of the same $tag. I want to show only articles that have all the same tags.

For exampel:

The group has as tags: laravel, php, html. Then I would like to let all articles, which have exactly the same tags. So all the articles with the tags laravel, php, html.

Not all articles with the only one same tag, only article with have all the same tags.

06 Sep
8 months ago

slickness left a reply on Linking Articles With Groups

@burlresearch how can i use the Code in the Controller?

05 Sep
8 months ago

slickness left a reply on Validate Error Message Ajax Call

The toast thing is similar to that: https://codeseven.github.io/toastr/

If i use that:

if (data.error) {
                            _toastr((data.error),"top-full-width","error",false);
                            console.log(data);
}

then it works. But the error messages are side by side and not on top of each other.

For exampel:

error 1 error 2

but it should be like that: error 1 error 2

if i use your code i get the follow in the console:

jquery-2.2.3.min.js:4 POST http://localhost/admin/tasks/store 500 (Internal Server Error)
send @ jquery-2.2.3.min.js:4
ajax @ jquery-2.2.3.min.js:4
(anonymous) @ tasks:4326
dispatch @ jquery-2.2.3.min.js:3
r.handle @ jquery-2.2.3.min.js:3
tasks:4340 field = readyState
jquery-2.2.3.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 4
    at s (jquery-2.2.3.min.js:2)
    at Function.each (jquery-2.2.3.min.js:2)
    at Number.<anonymous> (tasks:4343)
    at Function.each (jquery-2.2.3.min.js:2)
    at Object.error (tasks:4339)
    at i (jquery-2.2.3.min.js:2)
    at Object.fireWith [as rejectWith] (jquery-2.2.3.min.js:2)
    at z (jquery-2.2.3.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery-2.2.3.min.js:4)

slickness left a reply on Validate Error Message Ajax Call

@Cronix Thank you for your help. Unfortunately, it does not work yet, or I do not get it adjusted properly.

This is my error message:

_toastr((the error message is here),"top-full-width","error",false);

slickness started a new conversation Validate Error Message Ajax Call

I am currently working on ajax, jquery and javascript. I have slight problems with it.

How can I output the validate errors from laravel?

in the console, the errors are displayed. Example: The field xyz is required. The toastr message is only displayed without content.

Code

        <script type="application/javascript">
        $(document).ready(function () {
            var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

            $(document).on('click','#add-todo-list', function(e) {
                e.preventDefault();
                $('.todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
                    return event.keyCode != 13;
                });

                var _token = $("input[name='_token']").val(); // get csrf field.
                var title = $("input[name='title']").val();
                var description = $("textarea[name='description']").val();
                var privacy = $("select[name='privacy']").val();
                $.ajax({
                    url:'{{ route('todolists.store') }}',
                    type: 'POST',
                    data: {_token:_token, title:title, description:description, privacy:privacy},
                    dataType: 'json',
                    success: function (data) {
                        if (data.error) {
                            _toastr((data),"top-full-width","error",false);
                            console.log(data);
                        }
                        else{
                            $('.todolist-create-modal').modal('hide');
                            $("#wrapper").load(location.href+" #wrapper>*","");
                            _toastr((data),"top-full-width","success",false);
                            console.log(data);
                        }
                    }

                });
            });
        });
    </script>

Controller

public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|max:40',
            'description' => 'required|min:15',
            'privacy' => 'required|integer'
        ]);

        $attributeNames = array(
            'title' => 'Title',
            'description' => 'Description',
        );
        $validator->setAttributeNames($attributeNames);
        //Redirect back if validation fails
        if($validator->fails()) {
            return response()->json(['error'=>$validator->errors()->all()]);
        }
        else{
            $todolists = new Todolists();
            $todolists->admin_id = Auth::id();
            $todolists->title = $request->title;
            $todolists->description = $request->description;
            $todolists->privacy = $request->privacy;
            $todolists->save();

            return response()->json(['Your enquiry has been successfully submitted!'],200);

        }

    }
02 Sep
8 months ago

slickness started a new conversation Laravel Ajax Store Request Errormessage, Data Append To View

I'm new to ajax and I have two little problems.

how can I load the data directly into the view without reload the page? if the privacy is 1, the code should be displayed in the right column, and if the privacy is 0, the code should be displayed in the left column.

How can I output the error messages with my errormessage code?

view ´´´

Neue Liste erstellen Private Tasks Es wurden keine Einträge gefunden. @foreach ($todolistpublic as $list) {{ $list->title }} 0 {{ $list->description }} @endforeach {{ $todolistpublic->count() }} {{ $todolistpublic->count()> 1? 'Listen' : 'Liste' }}
    <div class="col-md-6">
        <div id="panel-misc-portlet-l3" class="panel panel-default text-center">
            <div class="panel-heading nohover">
                <span class="elipsis">
                    <strong>Öffentliche Tasks</strong>
                </span>
            </div>
        </div>
        <div class="alert alert-danger margin-bottom-30 {{ $todolistprivate->count() ? 'hidden' : '' }}">
            Es wurden keine <strong>Einträge</strong> gefunden.
        </div>
        @foreach ($todolistprivate as $list)
            <div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
                <div class="panel-heading panel-pointer">
                        <span class="elipsis"><!-- panel title -->
                            <strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
                        </span>
                    <ul class="options pull-right relative list-unstyled hover-visible">
                        <li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden"><i class="fa fa-plus"></i> Erstellen</a></li>
                        <li><a data-toggle="modal" data-target=".todolist-modal" class="btn btn-info btn-xs white hover-hidden"><i class="fa fa-edit"></i> Bearbeiten</a></li>
                        <li><a href="#" class="btn btn-danger btn-xs white hover-hidden"><i class="fa fa-times"></i> Löschen</a></li>
                        <li><a href="#" class="opt panel_colapse" data-placement="bottom"></a></li>
                    </ul>
                </div>
                <div class="panel-body">
                    <div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
                        {{ $list->description }}
                    </div>
                </div>
            </div>
        @endforeach
        <div class="panel-footer mtm-10">
            <span id="todo-list-counter-private">{{ $todolistprivate->count() }}</span> <span>{{ $todolistprivate->count() > 1? 'Listen' : 'Liste' }}</span>
        </div>
    </div>

    @include('elements.addTodoList')
    @include('elements.createTodoList')
    @include('elements.addTask')
</div>

$(document).ready(function () { var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $('#add-todo-list').click(function(e) {
        e.preventDefault();
        var _token = $("input[name='_token']").val(); // get csrf field.
        var title = $("input[name='title']").val();
        var description = $("textarea[name='description']").val();
        var privacy = $("select[name='privacy']").val();
        $.ajax({
            url:'{{ route('todolists.store') }}',
            type: 'POST',
            data: {_token:_token, title:title, description:description, privacy:privacy},
            success: function (data) {
                console.log(data);
            }
    });
    });
});

´´´

Controller ´´´ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required|min:5', 'description' => 'required|min:10', 'privacy' => 'required|integer' ]);

$attributeNames = array(
    'title' => 'Title',
    'description' => 'Description',
);
$validator->setAttributeNames($attributeNames);
//Redirect back if validation fails
if($validator->fails()) {
    return response()->json(['error'=>$validator->errors()->all()]);
}
else{
    $todolists = new Todolists;
    $todolists->admin_id = auth::user();
    $todolists->title = $request->title;
    $todolists->description = $request->description;
    $todolists->privacy = $request->privacy;
    $todolists->save();
    return response()->json(['success'=>'Your enquiry has been successfully submitted!']);

}

} ´´´

modal ´´´

×

Erstelle eine neue Liste

{{ csrf_field() }} Titelname Beschreibung
                    <i class="fa fa-comments"><!-- icon --></i>

                </div>
            </div>
            <div class="form-group">
                <label for="" class="control-label">Privatsphäre</label>
                <div class="fancy-form fancy-form-select">
                    <select id="privacy" name="privacy" class="form-control">
                        <option selected value="0">Öffentlich</option>
                        <option value="1">Privat</option>
                    </select>
                    <i class="fancy-arrow"></i>
                </div>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success" id="add-todo-list">Save changes</button>
    </div>
</div><!-- /.modal-content -->

´´´

errormessages ´´´ @if (count($errors) > 0) @foreach ($errors -> all() as $e) _toastr("{{$e}}","top-right","error",false); @endforeach @endif

@if (session('fail'))

_toastr("{{ session('fail') }}","top-full-width","warning",false); @endif

@if (session('status'))

_toastr("{{ session('status') }}","top-full-width","info",false); @endif

@if (session('success')) _toastr("{{ session('success') }}","top-full-width","success", false); @endif

@if (session('error')) _toastr("{{ session('error') }}","top-full-width","error",false); @endif ´´´

14 Aug
9 months ago

slickness left a reply on Linking Articles With Groups

@burlresearch I would like to show in the group all articles which have the same tags as the group. I do not know how I can realize that. How can I implement this? Do I need a many to may relationship and a pivot tabel for article_groups?

13 Aug
9 months ago

slickness started a new conversation Linking Articles With Groups

I have articles that can contain different tags. For example, 5 pieces: (php, html, css, laravel, js) And I have groups that can also contain different tags. For example 4 pieces: (laravel, php, html, css)

I have already defined the relationships and it works. What I still lack is the linkage of article to the group.

In the Articlecontroller i use this so sync:

$article->groups()->sync($group->id);

How can I link the right groups and articles with the same tags?

Article Model


      public function groups()
      {
        return $this->belongsToMany('App\Group');
      }
    
        public function tags()
        {
            return $this->morphToMany('App\Tag', 'taggable');
        }

Tag Model


    public function articles()
    {
        return $this->morphedByMany('App\Article', 'taggable');
    }
    
    public function groups()
    {
        return $this->morphedByMany('App\Group', 'taggable');
    }

Group Model


    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
    
    public function articles()
    {
        return $this->belongsToMany('App\Article');
    }

slickness left a reply on Pass Userdata To View

@cmdobueno I updated my question and added the models

slickness started a new conversation Pass Userdata To View

I show in a view all posts with a used tag. Now I want to represent all users, who wrote a post with this tag. I have no relationship between the tags and the user. The day has a relationship with the post, the post has an interest in the user and the user has a profile. How can I load the data?

Controller

    public function show($name)
    {
        $tag = Tag::where('name', $name)->first();
        if ($tag) {
            $user = ?????????->paginate(20);
            $mostvotedpost = $tag->posts()->where('type', 4)->first(); //only example add vote
        } else {
            return back()->with('success', lang::get('messages.nocontent'));
        }

        return view('tags.abo', compact('tag', 'user', 'mostvotedpost'));
    }
12 Aug
9 months ago

slickness started a new conversation Users Block By A User

Blocked users should not be able to visit each other's profile. I did that with a middleware. The problem is that the user can no longer visit his own profile through the middleware. Can someone help me?

The second question is, how can I prevent the user from following a blocked user? Is a middleware sufficient or should I do that in the follow function?

class CheckBlockUserByUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userslug = $request->slug;
        $user = User::where('slug', $userslug)->first();

        if (Auth::guest()) {
            return $next($request);
        }

        if ($user) {
            if ($user->isblocked() OR $user->isblocking()) {
                return redirect('/home');
            } else {
                return $next($request);
            }
        }

        return $next($request);
    }
}

Routes:

Route::get('/profile/{slug}', '[email protected]')->name('profile');
Route::post('profile/{profileId}/follow', '[email protected]')->name('user.follow');
Route::post('/{profileId}/unfollow', '[email protected]')->name('user.unfollow');
09 Aug
9 months ago

slickness started a new conversation Filter Posts By Type And Others

Currently I have all posts displayed on one page with different views. Now I would like to be able to filter the posts according to the post type in the different views. So that I only see posts with pictures, or only posts with a video ....

view:

Filter

<div class="pn-ProductNav_Wrapper">
                        <nav id="pnProductNav" class="pn-ProductNav">
                            <div id="pnProductNavContents" class="pn-ProductNav_Contents float-left">
                                <a href="#section_2" class="pn-ProductNav_Link" data-toggle="tab" aria-selected="true"><i class="glyphicon glyphicon-check fa-lg"></i> tookone</a>
                                <a href="#section_4" class="pn-ProductNav_Link" data-toggle="tab"><i class="glyphicon glyphicon-camera fa-lg"></i> Web</a>
                                <a href="#" class="pn-ProductNav_Link padding" data-toggle="tab" aria-selected="true"><i class="glyphicon glyphicon-check fa-lg"></i> All</a>
                                <a href="#" class="pn-ProductNav_Link" data-toggle="tab"><i class="glyphicon glyphicon-camera fa-lg"></i> Foto</a>
                                <a href="#" class="pn-ProductNav_Link" data-toggle="tab"><i class="glyphicon glyphicon-facetime-video fa-lg"></i> Video</a>
                                <a href="#" class="pn-ProductNav_Link" data-toggle="tab"><i class="glyphicon glyphicon-music fa-lg"></i> Audio</a>
                                <a href="#" class="pn-ProductNav_Link" data-toggle="tab"><i class="glyphicon glyphicon-align-justify fa-lg"></i> Text</a>
                                <span id="pnIndicator" class="pn-ProductNav_Indicator"></span>
                            </div>
                        </nav>
                        <button id="pnAdvancerLeft" class="pn-Advancer pn-Advancer_Left" type="button">
                        </button>
                        <button id="pnAdvancerRight" class="pn-Advancer pn-Advancer_Right" type="button">
                        </button>
                    </div>

Posts

<div class="alert alert-transparent bordered-bottom p-0">
                <div class="m-0">
                    <div class="row text-center">

                        <div class="col-md-4 col-sm-4 col-xs-4 pt-5">
                            <a href="#section_1" data-toggle="tab"><i class="glyphicon glyphicon-th fa-lg"></i></a>
                        </div>
                        <div class="col-md-4 col-sm-4 col-xs-4 pt-5">
                            <a href="#section_2" data-toggle="tab"><i class="glyphicon glyphicon-list fa-lg"></i></a>
                        </div>
                        <div class="col-md-4 col-sm-4 col-xs-4 pt-5">
                            <a href="#section_3" data-toggle="tab"><i class="glyphicon glyphicon-eye-close fa-lg"></i></a>
                        </div>
                    </div>
                </div>
                
                <div class="tab-content">
                    <div class="tab-pane active" id="section_1">
                        <div class="mtm-20"></div>
                        @include('elements/imagepost')
                    </div>
                    <div class="tab-pane fade" id="section_2">
                        @include('elements/posts_big')
                    </div>
                    <div class="tab-pane fade" id="section_3">
                        @include('elements/posts_anonym')
                    </div>
                    <div class="tab-pane fade" id="section_4">
                        <p>// display content from web</p>
                    </div>
    </div>
</div>

contoller

    public function show($name)
    {
        $tag = Tag::where('name', '#' . $name)->first();
        if ($tag) {
            $postall = $tag->posts()->with('comments', 'tags')->whereIn('privacy', [1, 2])->where('status', 1)->where('type', '!=', 7)->latest()->get();
        } else {
            return back()->with('success', lang::get('messages.nocontent'));
        }

        return view('tag', compact('tag', 'postall'));
    }

route

Route::resource('/tags', 'TagController');

is that possible with tabs? how can I implement this?

05 Aug
9 months ago

slickness left a reply on What Is The Best Way To Set Language For User

i reset the config cache. But i still have the same mistake.

this is the languages file from the config folder(config/languages.php)

    return [
    'en' => 'English',
    'de' => 'German',
    ];

slickness left a reply on What Is The Best Way To Set Language For User

I found the first error, I forgot to put the index page in the middleware.

Route::post('/changelanguage', '[email protected]')->name('changelanguage');

Route::group(['middleware' => 'translate'], function() {

//all other routes

});

Now I get the following error message:

"array_key_exists() expects parameter 2 to be array, null given"

slickness left a reply on What Is The Best Way To Set Language For User

I would like to read the language from the browser and give the user the additional possibility to change the language itself.

Unfortunately there is a mistake in my code and I can not find it. I get the following error message:

array_key_exists() expects parameter 2 to be array, null given

Middleware:

class SetLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if( !Session::has('locale' )){
            $browserLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); //read browser language

            if ( array_key_exists($browserLanguage, Config::get('languages')) ) {
                Session::set('locale', $browserLanguage);
            } else {
                Session::set('locale', 'en');
            }
        }

        //Simply set language from session
        App::setlocale(Session::get('locale'));

        return $next($request);
    }
}

Controller

class LanguageController extends Controller
{
    /**
     * Change session locale
     * @param  Request $request
     * @return Response
     */
    public function changeLanguage(Request $request)
    {
        $this->validate($request, ['lang' => 'required|in:de,en']);

        Session::put('locale', $request->lang);
        App::setlocale($request->lang);


        return redirect()->back();
    }

}

Form:

<a href="{{ route('changelanguage') }}"
           onclick="event.preventDefault();
                       document.getElementById('languageen').submit();">
          &bull; {{__('Englisch')}}
        </a>

        <form id="languageen" action="{{ route('changelanguage') }}" method="POST" style="display: none;">
          {{ csrf_field() }}
          <input type="hidden" name="lang" value="{{ 'en' }}">
        </form>

        <a href="{{ route('changelanguage') }}"
           onclick="event.preventDefault();
                       document.getElementById('languagede').submit();">
          &bull; {{__('Deutsch')}}
        </a>

        <form id="languagede" action="{{ route('changelanguage') }}" method="POST" style="display: none;">
          {{ csrf_field() }}
          <input type="hidden" name="lang" value="{{ 'de' }}">
        </form>

route

Route::post('/changelanguage', '[email protected]')->name('changelanguage');
04 Aug
9 months ago

slickness started a new conversation What Is The Best Way To Set Language For User

Hello, I would like to make a social media website multilingual. What is the best way to implement this if I want to use the lang folder?

15 Jul
10 months ago

slickness left a reply on Different Error Messages At Login

I changed the code, it only redirects me to a white page, and nothing happens

    protected function validateLogin(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'username' => 'requiered|string',
            'passwort' => 'requiered|string',
        ]);

        // retrieve the user
        $user = User::where('active','1')->firstOrFail();

        // check if the user is validated, if not create a 'validated' custom error
        $validator->after(function ($validator) use ($user) {
            if ( ! $user->validated) {
                $validator->redirect()->route('activate')->with('error', lang::get('messages.activatemail'));;
            }
        });
    }

slickness left a reply on Different Error Messages At Login

@Cronix thanks. My problem is, I do not know where to use the code or if I have to replace other code

slickness left a reply on Different Error Messages At Login

@Cronix thanks, your solution is good. Do you have a code example somewhere?

slickness started a new conversation Different Error Messages At Login

Hello everyone, I changed the login function a bit, that the user can only log in with his user name and his email if his email address was confirmed by a sent email. If the user wants to log in, I want to issue different error messages.

If the email address or the username is not available, I would like to give him the error message that his email address or username is not present. If his account has not yet been activated, I would like to forward him to one side and tell him that he must first activate his account.

How can I implement that? Does anyone have a similar code?

Logincontroller

 use AuthenticatesUsers;

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

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

    /**
    * Get the needed authorization credentials from the request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return array
    */
   protected function credentials(Request $request)
   {
       $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
           ? $this->username()
           : 'username';

       return [
           $field => $request->get($this->username()),
           'password' => $request->password,
       ];
   }
    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => [
                'required', 'string',
                Rule::exists('users')->where(function ($query){
                    $query->where('active', true);
                })
                ],
            'password' => 'required|string',
        ], $this->validationError());
    }

    /**
     * Get the validation error for login
     *
     * @return array
     */
    public function validationError()
    {
        return[
            $this->username() . '.exists' => 'the selected email or username is invalid, you need to activate it!'
        ];
    }

    public function userLogout()
    {
        Auth::guard('web')->logout();
        return view('/exit');
    }
}
14 Jul
10 months ago

slickness started a new conversation Scoring System User And Team

Hello to all, I would like to integrate a point system in my application. A user has a team and a team has many users. The tables and the team functionality already exists. For certain activities the user should get points. For example, if he publishes a post he should get 5 points, if he scores a post he should get 5 points and if the user writes a comment he also gets points. The team should get all points from its users. What is the best solution to integrate this?

20 Mar
1 year ago

slickness started a new conversation Structure Of Model, Controller Frontend And Backend

What is the right and best structure if I have posts, for example. The user can create posts in the frontend, which I want to manage in the backend. Then I have a post model, and a postcontroller for the frontend. Do I create a new controller for the backend? For example, adminpostcontroller, or do I use the postcontroller from the frontend?

07 Mar
1 year ago

slickness started a new conversation Save One To Many Without Creating

I just have a little problem. I have a one to many relationship. A team has many users. Many users have a team. I have six teams of which the user has to choose one. How can I connect the team with the user without creating a new entry in the database 'team'?

User:

id

name

Team:

id

name

slickness started a new conversation Redirect User When The Db Is Empty

I have a one to many relationship between user and team.

If a user registers, he will be forwarded to / welcome on the first login and must select a team.

The problem is that the user can bypass this process by entering another url from the side. How can I redirect the user from all pages to / welcome if he has not yet selected a team and how can I lock the page for the user if he has selected a team?