spoon

spoon

Member Since 3 Years Ago

Istanbul

Experience Points 4,100
Experience Level 1

900 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 40
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

03 Oct
3 years ago

spoon started a new conversation User Activation

Hello.

I have a strange problem that I can't solve.

When a user is registered, I redirect them to a feed url, open a modal and tell my users to activate their accounts by using the email that I sent them. But even if I open the activation url, I keep being redirected to the exact same page and my account isn't being activated. What could be the problem here?

routes.php

Route::group(['namespace' => 'Auth'], function () { Route::group(['middleware' => 'auth'], function () { Route::get('activate/{token}', 'PasswordController@activate'); }); });

PasswordController

public function activate($token) {
    //get token value.
    // find the user that belongs to that token.
    $activation = User::where("confirmation_code", $token)->get()->first();
    $activation->confirmed = 1;
    $activation->save();
}

RedirectIfAuthenticated.php If I remove feed url, it works. But I don't want to do that.

public function handle($request, Closure $next)
{
    if ($this->auth->check()) {

        return redirect('/feed');
    }

    return $next($request);
}
30 Sep
3 years ago

spoon started a new conversation Query Caching With Redis

Hello, I'm trying to activate caching with Redis.

Here's what I've done so far.

1-) Added predis/predis package via composer.

2-) Changed file to redis in config/cache.php

'default' => env('CACHE_DRIVER', 'redis')

3-) Tried to cache a query for 10 minutes.

$comments = Thing::with(array('comments' => function($query) use ($id)
            {
            }))->find($id)->comments()->simplePaginate(25);

Cache::put('comments', 'comments', 10);
return view('frontend.index')->with('comments', $comments);

I didn't change anything in the Redis section in database.php, should I change something in there? I reach my app like so : localhost:8000

    'redis' => [

        'cluster' => false,

        'default' => [
            'host'     => '127.0.0.1',
            'port'     => 6379,
            'database' => 0,
        ],

    ],

Am I using it right?

28 Sep
3 years ago

spoon started a new conversation NodeJS, Socketio And Redis

Hi.

I'm kinda confused about all of these, I hope I can get an answer.

Right now I use MySQL and Laravel and I want to add realtime notifications into my website, so I decided to use socketio.

1-) In order to use socketio, I need to install NodeJS first, right? 2-) I also need to use a framework like Express with NodeJS, is that correct? 3-) I always see tutorials and docs about socketio and Redis, doesn't it work with MySQL properly? Is there something wrong with MySQL while creating a realtime feature?

26 Sep
3 years ago

spoon started a new conversation Querying Multiple Tables, Merging Them And Ordering By Name

Hi.

The title says everything, actually. :)

I'm trying to create a basic search functionality, but there are more than one table that I need to query. How can I include users (or another) table into my existing script and order them by name?

    public function search(Request $request)
    {
        if (Request::ajax())
        {
            $keywords = Request::input("keywords");
            $arr = array();
            $results = Thing::where("original_name", "LIKE", "$keywords%")->orderBy('original_name', 'ASC')->take(10)->get();
            foreach($results as $result)
            {
                $arr[] = array('id' => $result->id, 'original_name' => $result->original_name);
              }

            echo json_encode($arr);
        }
    }

Here's my jQuery ajax code.

    $('#search').on('input', function () {
        var searchKeyword = $(this).val();
        if (searchKeyword.length >= 3) {
            $.post('/search', {keywords: searchKeyword}, function (data) {
                $('ul#content').empty();
                $.each(data, function () {
                    $('ul#content').append('<li><a href="example.php?id=' + this.id + '">' + this.original_name + '</a></li>');
                });
            }, "json");
        }
    });
21 Sep
3 years ago

spoon left a reply on Listing People Who Read A Magazine : Eloquent Query And Relationships

Thanks @bobbybouwmann

I don't have a readers table, I hold the data in thingprogress_thing pivot table in order to follow the naming convention. $id is the magazine ID. There's no repetition in any of my tables, I always use foreign keys.

I couldn't understand why you said that I should change my database structure, I would be very happy if you explain a little. I hold the magazines in the thing table, users in the users table, thing_progress table hold values (I'm reading / I've read) and thingprogress_thing merges them together (user_id, thing_id, thing_progress_id). Should I remove thing_progress table altogether?

Would it be a better solution if I query the pivot table directly?

spoon started a new conversation Listing People Who Read A Magazine : Eloquent Query And Relationships

I'm trying to get a list of the ID's of the users who read a particular magazine.

things table (magazines)
id
name

thing_progresses

id
progress_value

thingprogress_thing

id
thing_progress_id (FK from thing_progresses table)
thing_id (FK from things table)
user_id (FK from users table)

Thing Model

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Thing extends Model
{
    public function readers() {
        return $this->belongsToMany('\App\Models\ThingProgress', 'thingprogress_thing');
    }
}

My application

$readers = Thing::with(array('readers' => function($query) use ($id) {
$query->where('thing_progress_id', '1');
}))->find($id);

View

@foreach($readers as $reader)
    {{$reader->user_id}}
@endforeach

Here's the error I got.

Trying to get property of non-object (View: /Applications/MAMP/htdocs/master/resources/views/frontend/thing/book/index.blade.php)

What's wrong?

20 Sep
3 years ago

spoon started a new conversation Return Pretty JSON Data

Hi,

Here's my JSON. I want to return "pretty" values, but even though I use unescaped_unicode, if there's a new line in the column, it echoes by adding a \n, which I don't want it to. If I echo the value using regular ->with(), I don't see any errors or \n text in the output.

How can I clean everything from the JSON value?

public function comments($id) {
    $book = Thing::find($id);
    return Response::json($book, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
}

spoon left a reply on Eloquent Too Many Queries

@boynet, no, of course I don't. They don't appear on the views if you don't include them, do they?

spoon started a new conversation Eloquent Too Many Queries

Hi.

I'm trying to fetch covers of a book that belongs to an author. So far, so good. But it generates a separate query for each book and takes 2 seconds to load a page, I think I'm doing something wrong.

Is there a faster way to do this?

Image Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Image extends Model
{

    public function imageable()
    {
        return $this->morphTo();
    }
    
}

Thing Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Thing extends Model {

    public function cover() {
        return $this->morphMany('\App\Models\Image', 'imageable');
    }
}

Controller

// book cover
            $findcover = Thing::with(array('cover' => function($query) use ($id) {
                $query->where('imageable_type', 'App\Models\Thing')
                  ->where('imageable_id', $id);
            }))->find($id);

            $maincover = $findcover->cover;

return view('frontend.index')->with('allbooks', $allbooks)
        }

View

@foreach($allbooks as $allBooks)
                @foreach($allBooks->cover as $value)
                    <img class="hund" src="http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-252368.jpg" alt="">
                @endforeach
            @endforeach

** I return a wallpaper image to make a test since images aren't on my computer yet.

Image proof: http://i.imgur.com/K9ulqCB.png

spoon left a reply on Which OS Are Most Laravel Developers Using?

I've used Windows from 1998 to 2014 (98, XP, 7) and I loved it.

In 2014, I bought a Macbook Air and I loved it more.

Even though I'm not an experienced programmer, here's my setup : Macbook Air (OS X Yosemite) on the left for development, 17" external on the right for documentation. It really helps.

Sometimes I am thinking of getting a large third monitor for IDE and an external keyboard (a mechanical one like Razer Chroma), but I give up too quickly.

I use MAMP for development environment (phpMyAdmin & PHP).

16 Sep
3 years ago

spoon left a reply on Notifications Concept

This thread may help you : https://laracasts.com/discuss/channels/laravel/designing-an-activity-feed-and-fetching-results-from-it

It's about creating an activity feed, but I think it can be arranged to meet your needs.

15 Sep
3 years ago

spoon left a reply on How Do You Allow Users To Mark Lessons As Complete?

~~regardless of whether they are articles, or quizzes, or something else.~~

I think you need to watch this and look into polymorphic relations. https://laracasts.com/lessons/polymorphic-huh

This special relation type allows you to have only one table to hold everything (completed lessons, read articles, finished quizzes). If that's the case, polymorphic relations is the key to do.

If you want to create a pivot table if there's only one "thing" and "status", then you need to create a many-to-many relationship and a pivot table where user_id and article_id (or lesson_id) are foreign keys from their respected tables.

spoon left a reply on Cacade Delete Through A Polymorphic Relationship

I don't know whether it's a right thing to do, but I don't do it using Laravel.

I make my foreign keys as cascade (I use phpMyAdmin for that), so when I delete a user, everything about that user gets deleted.

13 Sep
3 years ago

spoon started a new conversation Compiling Bootstrap

Hello,

I downloaded Bootstrap 4 Alpha and as far as I understand, I need to compile it. There are some .scss files in the scss folder and I think I need to compile all of these into one file, but I don't know how to do.

NodeJS, npm and gulp are installed and when I run gulp from the command line, it compiles some stuff. How can I tell Laravel to compile everything in the resources/assets/bootstrap folder? Do I need to include every .scss file manually in the gulpfile.js or is there another way?

11 Sep
3 years ago

spoon left a reply on Polymorphic Relation, SQL Query Fetches Full Model Name Instead Of Its Name

@Ruffles, thank you, but I get the same result, it still seek for App\Models\Thing in the commentable_type column. I renamed records from Thing to App\Models\Thing and everything works, but I'd like to have just model name.

spoon started a new conversation Polymorphic Relation, SQL Query Fetches Full Model Name Instead Of Its Name

Hi,

I'm trying to implement this : https://laracasts.com/lessons/polymorphic-huh

My Models are in the Model table, so I use namespace.

comments table

id
commentable_id
commentable_type
comment
created_at

Comment Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    public function commentable()
    {
        return $this->morphTo();
    }
}

Thing Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;


class Thing extends Model
{
    public function comments() {
        return $this->morphMany('\App\Models\Comment', 'commentable');
    }
}

If I use like this, it seeks for App\Models\Thing rather than Thing in the commentable_type column.

select * from comments where comments.commentable_id = '1' and comments.commentable_id is not null and comments.commentable_type = 'App\Models\Thing'

Controller

$comments = Thing::FindorFail($id)->comments;

View

@foreach($comments as $comment)
    {{$comment->comment}}
@endforeach

How can I solve this?

10 Sep
3 years ago

spoon left a reply on Designing An Activity Feed And Fetching Results From It

@ohffs, I'm trying to understand your answer, it's been a long day for me, too. The way you're saying, I need to create an additional table called feeds and relate activity_id's with user_id's, is that correct?

Thank you for your answer.

spoon left a reply on Designing An Activity Feed And Fetching Results From It

I will be using polymorphic relations for likes, shares, comments and images. That part is handled, but I don't know how to include groups and events and order them by date with user updates, as I've explained above.

spoon started a new conversation Designing An Activity Feed And Fetching Results From It

Hello.

'm trying to design an activity feed, but I have a small problem.

Here's my current table.

activity

id
user_id
status
activitytype_id (status, video, photo, etc)
created_at
location
video
I didn't add some unrelated columns to make it short.

This works when I want to create a feed for the friends' posts of a user. I basically create an array with PHP and check for user_id's in the activity table and sort them by date.

But a user also follows groups and events, this is the tricky part.

What's the best way to include them (groups and events) in the feed? I can add a column to the activity called event_post and group_post and add posts id's as foreign keys to the activity table (null by default), but I'd like to hear your opinions.

If I query the community_user table (user_id and community_id as foreign keys) and get the list of groups a user follows, I will need to create a second query for group activity from the activities table in addition to user activity. Can I merge them together (they both have created_at columns since they're in the same table) and order by date? I'm new to laravel and I want to learn whether it's possible or not, also a good way or not.

communities

id
communitytype_id (group or event)
name
created_at
user_id (FK from users table, owner of the group or event)
09 Sep
3 years ago

spoon started a new conversation How Should I Name My "friends" Table?

Hello.

I used to follow my own convention but I decided to restructure my database to follow Laravel's own convention, so things will be more easy to deal with for me. However, I bumped into an issue.

I need to create a pivot table to contain a relation about friends. Here's my existing table, how should I rename it and its columns?

friendship

friend_one (foreign key from users table, user_id)
friend_two (foreign key from users table, user_id)
status
created_at
08 Sep
3 years ago

spoon started a new conversation Database Modeling

Hey,

I have two tables, event and group. There will be probably a few additional tables will be added like these, like "forum".

I'm creating a feed, so I'll have to collect data from all these tables. If I keep them like they are, there will be many tables in the database (up to 10, probably), and I also will need to merge results while displaying in the feed.

On the other hand, if I create a table called types and add type_id as foreign key to a one table and keep everything in the, there'll be less tables but I will have to create many columns.

Which one should I go with?

spoon left a reply on Get A Twitter Like Stream Of Data

Hey!

I've just implemented that feature yesterday. Since your setup is different from mine, I can give you only a partial example.

I'm dealing with three tables : users, user_status and friendship.

users user_id name email

friendship friendship_id friend_one (you) friend_two (your friend) status (0/1 = request sent / friends)

user_status status_id status status_type (status, photo, video, became friends, followed, etc) second_user (This is a foreign key from users table (user_id) BUT it's null by default. If status_type is became friends or followed, I check this one out)

User Model

public function friends() { return $this->belongsToMany('App\Models\User', 'friendship', 'friend_one', 'friend_two'); }

UserStatus model public function status() { return $this->belongsTo('\App\Models\User','user_id'); }

I get a user's friends like this : $friends = Auth::user()->friends; Convert it to an array $convert_to_userid = $friends->lists('user_id'); And fetch the statuses from user_status table $statuses = UserStatus::whereIn('user_id', $convert_to_userid)->orderBy('status_date','asc')->get();

spoon started a new conversation Questions About Creating An API

Hi,

As some of you know me from my previous questions, I'm kinda new to Laravel and still learning.

I develop my app without using RESTFUL resource controller for now.

Let's say there'll be an app of my website, my app will consume content from the website using the API, so we won't have to write it all over from scratch for iOS and Android, am I correct?

How do I go about this? I will develop my website using Laravel and use a package like below to create an API (in Controllers/Api folder) separately from the website, right?

https://github.com/dingo/api

07 Sep
3 years ago

spoon left a reply on Restrict File Download From Storage Directory

@ohffs is right.

As long as you aren't Netflix or something, you don't even need to worry about that.

05 Sep
3 years ago

spoon left a reply on HasMany Foreign Key And Local Key

@jakeryansmith

Yes, Laravel looks for a primary key called id by default, but I already override it in my ThingComment model ( protected $primaryKey = 'comment_id'; ) . Does that mean I don't need to add a primary key to my relations in that specific model (for instance, ThingComment) and I'm okay as it is?

spoon started a new conversation HasMany Foreign Key And Local Key

Hi, I'm confused about hasMany.

I have a model called Thing. A thing can have many comments and a comment belongs to a thing, I got it.

thing table

thing_id
original_name

thing_comment table

comment_id
thing_id (foreign key from thing table)
comment
created_at
updated_at

Here's what I have now. Thing model

    public function comment()
    {
        return $this->hasMany('\App\Models\ThingComment','thing_id');
    }

ThingComment model

    public function commentThing() {
        return $this->belongsTo('\App\Models\Thing','thing_id');
    }

My test script is below and it works without an issue, but the Laravel docs says that you need to put your foreign key first, then local key. If I add local key (comment_id) after thing_id in the Thing model, I only get a white, blank page.

Why does it happen?

Route::get('comments', function() {
    $comments = App\Models\Thing::find(100120)->comment;
    foreach ($comments as $comment) {
        echo $comment->comment;
    }
});

spoon left a reply on How Do I Store 'article_id' In 'images' Table Before That Article Has Been Created?

I am trying to upload multiple images using Dropzone on the create article view. The problem is the Dropzone plugin submits the image to the database as soon as I drag/drop it into the box

Have you tried this? https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button

spoon left a reply on Eloquent Where

@bobbybouwmann

I never close Laravel docs tab, but you are right.

I added a semicolon and this version works.

        $findBooks = User::with(array('usersBooks1' => function($query) {
            $query->where('progress_id', '=', 1);
        }))->find($user_id);
        $allBooks = $findBooks->usersBooks1;

spoon left a reply on Eloquent Where

@bobbybouwmann It doesn't work, I think you forgot to put the curly braces, so I tweaked it a little bit. I get Undefined variable: allbooks error.

        $user = User::with(array('userBooks1' => function($query)
        {
            $query->where('progress_id', '=', 1)->find($user_id);

            $allBooks = $user->usersBooks1;
        }));

spoon started a new conversation Eloquent Where

Hi!

I want to get the all books that has been read by a user, but I kinda stuck here. My usersxbook_progress table has three columns and they are foreign keys. user_id, progress_id and thing_id. progress_id = 1 means that book is completed, but how do I list only completed books by a user?

User Model

    public function usersBooks1() {
        return $this->belongsToMany('App\Models\Thing', 'usersxthing_progress','user_id','thing_id');
    }


Controller
    $allbooks = User::find($user_id)->usersBooks1;

View

@foreach($allbooks as $books) {{$books->name}} @endforeach

04 Sep
3 years ago

spoon left a reply on Listing Friends Of A User

@anzze Thank you very much.

spoon left a reply on Listing Friends Of A User

@anzze , I created the relationship you gave in the User model but I still get the same error. Undefined property: Illuminate\Database\Eloquent\Builder::$friends

spoon left a reply on Listing Friends Of A User

@gwp now I get another error called "Call to undefined method Illuminate\Database\Query\Builder::friends()"

spoon started a new conversation Listing Friends Of A User

Hi, I'm trying to list all friends of a user, but I'm stuck.

users table user_id name etc.

friendship table friendship_id friend_one (user_id as foreign key) friend_two (user_id as foreign key)

User.php Model (I removed everything but relationship)

<?php namespace App\Models;

class User {
    public function friends() {
        return $this->belongsToMany('\App\Models\Friendship', 'friendship','friend_one', 'friend_two');
    }

UserController.php

$friends = Friendship::where('friend_one', Auth::user()->user_id)->friends;
return view('test')->with('friends', $friends);

View

@foreach($friends as $friend)
    {{$friend->user_id}}
@endforeach

Here's the error I got : Undefined property: Illuminate\Database\Eloquent\Builder::$friends

02 Sep
3 years ago

spoon left a reply on Duplicate Query

@pmall

Now I got it.

Removing get() from $books solved the issue.

spoon left a reply on Duplicate Query

@pmall I want to fetch only one book.

http://localhost:8000/book/153824/letters-to-milena

When I open that url, I pass 153824 to my controller but I can't get that particular book's info. What's wrong here?

spoon started a new conversation Duplicate Query

Hello.

No matter what I do, all the books are being fetched from the database. Laravel DebugBar warned me and I started investigating this, but couldn't find the reason.

Main.php (My router)

Route::group(['namespace' => 'Book', 'prefix' => '',], function()
{
    Route::get('book/{id}/{slug}', 'BookController@bookIndex');
});

Here's my BookController.php

<?php
namespace App\Http\Controllers\Frontend\Book;
use App\Models\ThingComment;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Thing;
use App\Models\User;
use App\Models\UserImage;
use App\Models\Person;
use App\Models\BookxAuthor;


class BookController extends Controller
{

    public function bookIndex($id, $slug)
    {

        $request_slug = Thing::find($id)->slug;

        if ($slug !== $request_slug)
        {
            return redirect("book/$id/$request_slug");

        }  else
        {
            $books = Thing::find($id)->get();
            $authors = Thing::FindorFail($id)->person;
            $cover = Thing::FindorFail($id)->thingImage;
            $comments = ThingComment::where('thing_id', $id)->orderBy('comment_date', 'desc')->get();

            return view('frontend.book.index')
              ->with('books', $books)
              ->with('authors', $authors)
              ->with('cover', $cover)
              ->with('comments',$comments);
        }
    }
}

index.blade.php

{{-- book info --}}
@foreach($books as $book)
    <p>{{$book->turkish_name}}</p>
    <p>{{$book->original_name}}</p>
    <p>{{$book->publication_date}}</p>
    <p>{{$book->turkish_synopsis}}</p>
    <p>{{$book->book_language}}</p>
    <p>{{$book->original_language}}</p>
    <p>{{$book->number_of_pages}}</p>
    <p>{{$book->isbn}}</p>
    <p>{{$book->release_date}}</p>
@endforeach


{{-- author--}}

@foreach($authors as $author)
    <p>{{$author->person_name}}</p>
@endforeach

{{-- cover --}}
@foreach($cover as $bookcover)
    <p>{{$bookcover->value}}</p>
@endforeach


{{-- comments --}}
@foreach($comments as $comment)
    {{$comment->comment}}
    {{$comment->thingCommentOwner->name}}
    {{$comment->thingCommentOwner->defaultAvatar->value}}
    <p></p>
@endforeach

spoon started a new conversation A Simple Activity Feed

Hello.

I'm basically trying to create a an activity feed, but I couldn't figure out how to list only friends' updates.

I have two tables.

user_status

status_id status status_date

friendship

friend_one (FK from users table) friend_two (FK from users table)

friend_one is our logged in user, friend_two is his friend. Since one user can have many friends, friendship a junction table.

I know how to "jump" from one table to another and fetch the result, but this one is new to me.

30 Aug
3 years ago

spoon left a reply on Eloquent Relationships Assistance From Experienced Artisan

I wouldn't have created a new table since the admin is also a user. I think adding a column called is_admin (0/1, 0 as default) would suffice. In that case, something like below would be enough. I'm also new, but I don't see any drawback of using it as long as you protect your is_admin column via model (guarded or fillable) http://laravel.com/docs/5.1/eloquent

$globalarticles = App\User::where('is_admin', 1)->orderBy('created_date', 'desc')->get();
foreach($globalarticles as $globalarticle) {
    echo $globalarticle->article; // It's a very simple example.
}

I'll copy a few examples I've created this morning. Model names and Controllers are different but I think you'll be able to solve it and learn from it. I'm editing my answer right now.

29 Aug
3 years ago

spoon left a reply on Eloquent Many To Many Relationships

It started working when I change the order or person_id and thing_id in the relationships. I didn't know that the order is important.

I learned something new.

spoon started a new conversation Eloquent Many To Many Relationships

Hi,

I have a basic problem. Last week I've asked a similar question but I stuck again.

person -> person table thing -> book table bookxauthor -> junction table (person_id and thing_id are foreign keys)

I'm trying to get a book's authors using a book's id, but my count() echoes 0.

What's wrong here?

$author = Thing::FindorFail($id)->person;
            echo $author->count();

Here are my models.

Thing.php
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Thing  {

  /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'thing';
    protected $primaryKey = 'thing_id';


    public function person() {
        return $this->belongsToMany('\App\Models\Person', 'bookxauthor','person_id','thing_id');
    }
}

Person.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Person extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'person';
    protected $primaryKey = 'person_id';

    protected $fillable = ['person_name', 'alsoknownas', 'formalname', 'bornin', 'bornwhere', 'height', 'about'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */

    public function thing() {
        return $this->belongsToMany('\App\Models\Thing', 'bookxauthor','person_id','thing_id');
    }
}

BookxAuthor.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class BookxAuthor extends Model {

    protected $table = 'bookxauthor';
    protected $primaryKey = 'bookxauthor_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['person_id', 'thing_id'];

}

spoon left a reply on Laracast - Not Impressed

Hello @CarlosJa!

I think you're feeling that way because you've just started. Learning a framework from scratch can be challenging for some people even if it's like more welcoming than other frameworks and it takes time to put all the parts together.

I suggest you to learn by watching the whole series, not just separate lessons. https://laracasts.com/series

27 Aug
3 years ago

spoon left a reply on Fetching Data From A View

@kclark6595, I'm also new to Laravel, but I'll try my best.

Here's what you need to display data. 1-) A model 2-) A view (You can also display data without using a view) 3-) A controller

Here's my example, I hope you understand better.

Let's define a route. Route::get('users', 'DashBoardController@listUsers');

Create a function inside your DashBoardController. Here's my DashBoardController.php file. I added App\Models\User because I'm using the User model that lives in the App\Models folder.

use App\Http\Controllers\Controller;

class DashboardController extends Controller { public function listUsers() { $users = User::all(); return view('backend.admin.user.index')->with('users', $users); }

}

If you want to add multiple views, just add another with. return view('backend.admin.user.index') ->with('users', $users) ->with('random',$variable); ;

index.blade.php (This file is in the views/backend/admin/user folder, check out the dots above! We use dots instead of slash here.)

@foreach($users as $user) {{$user->user_id}} // I echo all of the ID's in my users table. @endforeach

25 Aug
3 years ago

spoon started a new conversation Class JavaScript Does Not Exist With BoilerPlate

Hi.

This is the error I get :

Class JavaScript does not exist```

I'm using the project : https://github.com/rappasoft/laravel-5-boilerplate

I tried to merge my existing app into this one, but I'm getting this error when I try to open the homepage of the app, which lives in the localhost:8000. 

I used composer update and composer dump-autoload -o , then I started getting this error.

Here's my composer.json file

{ "name": "laravel/laravel", "description": "The Laravel Framework.", "keywords": [ "framework", "laravel" ], "license": "MIT", "type": "project", "require": { "php": ">=5.5.9", "laravel/framework": "5.1.", "laravelcollective/html": "5.1.", "barryvdh/laravel-ide-helper": "^2.0", "barryvdh/laravel-debugbar": "^2.0", "intervention/image": "^2.3", "cviebrock/eloquent-sluggable": "^3.0" }, "require-dev": { "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.", "phpunit/phpunit": "~4.0", "phpspec/phpspec": "~2.1", "xethron/migrations-generator": "dev-l5", "way/generators": "dev-feature/laravel-five-stable", "phpdocumentor/phpdocumentor": "2.", "laracasts/generators": "^1.1" }, "autoload": { "classmap": [ "database" ], "psr-4": { "App\": "app/" } }, "autoload-dev": { "classmap": [ "tests/TestCase.php" ] }, "scripts": { "post-install-cmd": [ "php artisan clear-compiled", "php artisan optimize" ], "post-update-cmd": [ "php artisan clear-compiled", "php artisan optimize" ], "post-root-package-install": [ "php -r "copy('.env.example', '.env');"" ], "post-create-project-cmd": [ "php artisan key:generate" ] }, "config": { "preferred-install": "dist" },

"repositories": [ { "type": "git", "url": "git@github.com:jamisonvalenta/Laravel-4-Generators.git" } ] }


config/app.php

return [

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', true),

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => 'http://localhost',

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY', '58wxn7F95IUknqVY7fhrQM7OKljCIZwT'),

'cipher' => 'AES-256-CBC',

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/

'log' => 'single',

/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/

'providers' => [

  /*
   * Laravel Framework Service Providers...
   */
Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Routing\ControllerServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Collective\Html\HtmlServiceProvider::class,

  /*
   * Application Service Providers...
   */
Barryvdh\Debugbar\ServiceProvider::class,
Intervention\Image\ImageServiceProvider::class,
App\Providers\AppServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Way\Generators\GeneratorsServiceProvider::class,
Xethron\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,
Cviebrock\EloquentSluggable\SluggableServiceProvider::class

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

'App'       => Illuminate\Support\Facades\App::class,
'Artisan'   => Illuminate\Support\Facades\Artisan::class,
'Auth'      => Illuminate\Support\Facades\Auth::class,
'Blade'     => Illuminate\Support\Facades\Blade::class,
'Bus'       => Illuminate\Support\Facades\Bus::class,
'Cache'     => Illuminate\Support\Facades\Cache::class,
'Config'    => Illuminate\Support\Facades\Config::class,
'Cookie'    => Illuminate\Support\Facades\Cookie::class,
'Crypt'     => Illuminate\Support\Facades\Crypt::class,
'DB'        => Illuminate\Support\Facades\DB::class,
'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
'Event'     => Illuminate\Support\Facades\Event::class,
'File'      => Illuminate\Support\Facades\File::class,
'Hash'      => Illuminate\Support\Facades\Hash::class,
'Input'     => Illuminate\Support\Facades\Input::class,
'Inspiring' => Illuminate\Foundation\Inspiring::class,
'Lang'      => Illuminate\Support\Facades\Lang::class,
'Log'       => Illuminate\Support\Facades\Log::class,
'Mail'      => Illuminate\Support\Facades\Mail::class,
'Password'  => Illuminate\Support\Facades\Password::class,
'Queue'     => Illuminate\Support\Facades\Queue::class,
'Redirect'  => Illuminate\Support\Facades\Redirect::class,
'Redis'     => Illuminate\Support\Facades\Redis::class,
'Request'   => Illuminate\Support\Facades\Request::class,
'Response'  => Illuminate\Support\Facades\Response::class,
'Route'     => Illuminate\Support\Facades\Route::class,
'Schema'    => Illuminate\Support\Facades\Schema::class,
'Session'   => Illuminate\Support\Facades\Session::class,
'Storage'   => Illuminate\Support\Facades\Storage::class,
'URL'       => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View'      => Illuminate\Support\Facades\View::class,
'Form'      => Collective\Html\FormFacade::class,
'Html'      => Collective\Html\HtmlFacade::class,
'Debugbar'  => Barryvdh\Debugbar\Facade::class,
'Image'     => Intervention\Image\Facades\Image::class,

],

];

22 Aug
3 years ago

spoon left a reply on CSRF, Ajax And Security

I edited my second question to explain what I want to know it more clear.

19 Aug
3 years ago

spoon left a reply on Eloquent Sluggable

I should have been more careful. Thank you.

spoon started a new conversation Eloquent Sluggable

Hi.

https://github.com/cviebrock/eloquent-sluggable

I'm trying to install the package above. But when I add implements like below, PhpStorm gives an error states that "class must be declared abstract or implement methods resluggify, sluggify, getSlug". Is the docs old?

Here's my model. (it's in Models folder so I use a namespace)

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;

class Thing extends Model implements SluggableInterface
{
    protected $table = 'thing';
    protected $primaryKey = 'thing_id';

    protected $sluggable = [
      'build_from' => 'original_title',
      'save_to'    => 'slug',
    ];
    }
}

I also added it to my config/app.php like below. Cviebrock\EloquentSluggable\SluggableServiceProvider::class

I'm still new to Laravel5 and OOP PHP, trying to learn.

spoon left a reply on Is There A Package Or Project To Create Eloquent Relations Automatically?

@pmall , just to make things clear, are we talking about column names or column values here? I didn't even test it after I read it. If it's not the latter, then it wouldn't be a problem for me.