zoldic

zoldic

Member Since 1 Year Ago

Experience Points 1,660
Experience Level 1

3,340 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 1
Lessons
Completed
Best Reply Awards 1
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.

13 Dec
1 year ago

zoldic left a reply on Query Vs ForEach Loop, Which One Has The Better Performance?

Thanks for cloudhorizon & kobear for the reply & advice

09 Dec
1 year ago

zoldic left a reply on Query Vs ForEach Loop, Which One Has The Better Performance?

My bad, I make a little mistake with my code, I have fixed it

It is not

$reply = Reply::find($replyId);

the correct one is this

$reply = Reply::find($request->id);

zoldic left a reply on Query Vs ForEach Loop, Which One Has The Better Performance?

Yes, they have relationship already, the reply and like has onetomany relationship, a reply can have many likes and a like belong to a reply

zoldic left a reply on Query Vs ForEach Loop, Which One Has The Better Performance?

Hi thanks crnkovic for replying

1, What do you mean by "Always narrow down queries down to specific conditions you need". Can you give me an example about it using my previous scenario?

2, BTW, the reply and like has onetomany relationship, a reply can have many likes and a like belong to a reply.

so for eg. I have 5,000 replies in my DB, and 10,000 likes in my DB

and for eg. in reply id 2000, the reply has 10 likes, and using my previos function code scenario 1or2, if the current auth user has like the reply id 2000 it will return $likeByUser record and if there is none it will return null

Shouldn't it be the scenario1 will search all the records while scenario2 will only loop through 10likes from reply id 2000? so scenario2 should be faster?

Thanks

zoldic started a new conversation Query Vs ForEach Loop, Which One Has The Better Performance?

Hi folks, I'm wondering between Query vs Foreach loop, Which one has the better performance?

Here is a simple example, my web app, has a reply table and like table, the reply and like has onetomany relationship, a reply can have many likes and a like belong to a reply

and in this function I need to get a like record/model that is liked by current auth user

1, Using query

public function likeReply(Request $request)
{
    $reply = Reply::find($request->id);

    $likeByUser = Like::where([
            ['user_id', '=', Auth::id()],
            ['likeable_type', '=', 'App\Reply'],
            ['likeable_id', '=', $reply->id],
        ])->first();  //The Query

    //other line of code
}

2, Using foreach loop

public function likeReply(Request $request)
{
    $reply = Reply::find($request->id);
    
    $likeByUser = null;
    foreach($reply->likes as $like)
    {
            if($like->user_id == Auth::id() &&
            $like->likeable_type == 'App\Reply' &&
            $like->likeable_id == $replyId)
            {
                $likeByUser = $like;
                break;
            }
        }  //The Foreach loop

    //other line of code
}

Both method can get the like record/model that is liked by current auth user (it has the same result)

But I'm wondering which one has a better perfomance (speed, etc), if for eg. in my like table has 10,000 likes record in the DB? and if you know which one perform better, can you give me a simple explanation why it has better perfomance?

Thanks

05 Dec
1 year ago

zoldic left a reply on Get UserId With UserName Without Query

I just want to reduce the usage of query if possible

in this case

$userId = User::where('name', $name)->first()->id;

What do you mean by "storing that relationship elsewhere"?

can you give an example of that, using the id and name from the user_table

zoldic left a reply on Get UserId With UserName Without Query

No, it is not the logged in user

So it is not possible

zoldic started a new conversation Get UserId With UserName Without Query

Hi guys; Do you guys know how to Get UserId with UserName without query?

The regular way with query in the controller file

public function testing($name)
{
    $userId = User::where('name', $name)->first()->id;
}

is there any better way to get the id without the query? Thanks

26 Nov
1 year ago

zoldic started a new conversation How To Count A User's Gained Upvotes/likes?

Hi folks, I want to get the total count of a user's gained upvotes/likes from his replies

But I still can't figure it out

obviously using this won't work {{ $user->replies->likes->count() }}, it will return collection error

so I change it to this

@foreach($user->replies as $reply)
    {{ $reply->likes->count() }}
@endforeach

so for eg. a user has 3 replies, reply1 has 2 likes, reply2 has 5 likes, reply3 has 3 likes, and the total likes he got is 10 likes

and the above code will resulting this 2 5 3 in my view

so how can I increment it? so it will print 10 instead of 2 5 3

24 Nov
1 year ago

zoldic left a reply on Create Slug + Id

Can you give an example about it?

zoldic left a reply on Create Slug + Id

Thanks to everyone that has reply to this thread

Both solution works great, but sorry, the forum only let me choose one correct answer

23 Nov
1 year ago

zoldic left a reply on Create Slug + Id

So it is impossible to get the current created thread id?

So I guess this is the right code

    $thread = Thread::create([
            'user_id' => Auth::id(),
            'question' => $request->question,
            'embed' => $request->embed,
            'description' => $request->description,
            'slug' => 'slug'
        ]);

        $thread->update([
            'slug' => $thread->id . '-' . str_slug($request->question)
        ]);

zoldic started a new conversation Create Slug + Id

Hi guys, I want to make a slug + thread id for my thread

I want to make the slug look like this: web.com/thread/ThreadId-ThreadTitleInSlugForm

so for eg. web.com/thread/123-this-is-title

this is my currect thread create

$thread = Thread::create([
            'user_id' => Auth::id(),
            'question' => $request->question,
            'embed' => $request->embed,
            'description' => $request->description,
            'slug' => str_slug($request->question)  //this is the code that need to be changed
        ]);

Thanks

15 Nov
1 year ago

zoldic left a reply on What Is The Purpose Of Using & Registering Service Providers?

Hi thanks for the explanation

BTW, can you (or anyone) maybe give me a simple example using my previous example "dump.php" and register it as 'Service Providers', and how to call it, I want to see the difference between registering with 'aliases' and 'Service Providers'

Thanks

14 Nov
1 year ago

zoldic started a new conversation What Is The Purpose Of Using & Registering Service Providers?

Hi guys, I'm kinda confuse with Service Providers, I have no idea what is the purpose of using & registering Service Providers (yes, I have read the laravel's doc but I still don't quite get it), it is for calling a class with its method easier

I know how to register class to aliases in config/App.php, and it help you to easier calling the custom class with its method (you don't need to keep importing it with "use namespace" on top of your controller file)

for eg. I make this custom class name called "dump.php" and put it inside new folder called "Customs" (App\Customs\Dump.php)

namespace App\Customs;

class Dump
{
    public static function diedump($var)
    {
        dd($var);
    }
}

register it inside aliases in the config\app.php

'aliases' => [
    ...
    'Dump' => App\Customs\Dump::class,
],

so if I want to use it on one of my controller file, I can simply use the '' to call the class's method (Dump's diedump method)

//use App\Customs\Dump.php;  //don't need to import this anymore

class ThreadController extends Controller
{
    public function index() {
        $var = "dumpthis";
        \Dump::diedump($var);
    }
}

So for the Service Providers, what's the point of registering it? any difference with the aliases?

Can you guys give me simple example & explanatin about it?

Thanks

11 Nov
1 year ago

zoldic left a reply on Custom Validation Error (Method [validate] Does Not Exist On Redirect)

btw, this is the default RegisterController.php, before I add my custom validation code

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

it return the Validator, so I thought that I should return it too after the validation is passed (after it pass the "if ($validator->fails()) {...}"

Btw I still can't figure out how to solve this "Method [validate] does not exist on Redirect." error

I believe the error comes from the "return redirect()->back()" (I followed that from laravel doc), I have no idea why redirect back can cause error cause usually I use it for my other code and it work just fine

laravel doc

https://laravel.com/docs/5.4/validation#manually-creating-validators

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }

BTW, I have use the custom validation on my other model controller, just like the laravel doc with the redirect and it worked just fine,

The error only happen to RegisterController.php somehow

I think the default RegisterController.php has its own "if ($validator->fails()) {...}" code already hiding somewhere in the laravel files, does anyone know where it is?

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

zoldic left a reply on How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

Queries? I think this is the line of code that has queries in it

foreach(Thread::all() as $thread)
{
    if($thread->hasCorrectAnswer())
    {
        array_push($items, $thread);
    }
}

where hasCorrectAnswer is

public function hasCorrectAnswer() {
    return $this->replies->where('correct_answer', 1)
->first()['correct_answer'];
}

zoldic started a new conversation Custom Validation Error (Method [validate] Does Not Exist On Redirect)

Hi folks, I use the custom validation error so I can Name my Error Bags. I have follow laravel doc, but I got an error

P.S. I need to name my error bags because I have multiple form on the same page, register and login

(1/1) BadMethodCallException
Method [validate] does not exist on Redirect.
in RedirectResponse.php (line 234)
at RedirectResponse->__call('validate', array())
in RegistersUsers.php (line 34)

etc

my code the default RegisterController.php

https://laravel.com/docs/5.4/validation#manually-creating-validators

protected function validator(array $data)
    {
        $validator = Validator::make($data, [
            'name' => 'required|string|max:255|unique:users',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'g-recaptcha-response' => 'required|captcha',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()
                        ->withErrors($validator, 'register')
                        ->withInput();
        }

        return $validator;
    }

do you guys know how to fix this error?

05 Nov
1 year ago

zoldic left a reply on How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

Thanks to everyone that has been helping out

I managed to solve it now

$items = array();
foreach(Thread::all() as $thread)
{
    if($thread->hasCorrectAnswer())
    {
        array_push($items, $thread);
    }
}

$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 11;

$items = array_reverse(array_sort($items , function ($value) {
    return $value['created_at'];
}));
$currentItems = array_slice($items, $perPage * ($currentPage - 1), $perPage);

$paginator = new LengthAwarePaginator($currentItems, count($items), $perPage, $currentPage);
$results = $paginator->appends('filter', request('filter'));
break;

Another guide from jlrdw https://laracasts.com/discuss/channels/guides/length-aware-paginator

zoldic left a reply on How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

The reason is because I can't really query my Thread model directly, I loop all my thread is to check whether a single thread has a reply that has been mark as correct answer (a thread with a correct answer)

the hasCorrectAnswer() method in my Thread.php model

public function hasCorrectAnswer() {
    return $this->replies->where('correct_answer', 1)
->first()['correct_answer'];
}

I want to query it in the first place, but I believe it is not possible (CMIIW)

BTW the LengthAwarePaginator already worked, I just have problem with ordering/sorting it based on the created_at date

zoldic left a reply on How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

Thanks for the help

I have fixed my code, but I still have problem, I can't orderby/sortby my thread based on created_at

->orderBy('created_at', 'desc')

$items = array();
foreach(Thread::all() as $thread)
{
    if($thread->hasCorrectAnswer())
    {
        array_push($items, $thread);
    }
}

$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 11;
$currentItems = array_slice($items, $perPage * ($currentPage - 1), $perPage);

$paginator = new LengthAwarePaginator($currentItems, count($items), $perPage, $currentPage);
$results = $paginator->appends('filter', request('filter'));

zoldic left a reply on How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

It is for filter thread, just like laracast, filter: my question, my participation, my favorites, etc

in my case, for my filter solved it would be like this

web.dev/?filter=solved
web.dev/?filter=solved&page=1  //next page filter
web.dev/?filter=solved&page=2

this code work just fine

$results = Thread::where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(15)->appends('filter', request('filter'));

but I have no idea how to use the LengthAwarePaginator and how to add "appends" and "orderBy"

zoldic started a new conversation How To Use LengthAwarePaginator (Manual Paginator) With Appends & Sortby/orderby

Hi folks, I have no idea how to use the LengthAwarePaginator (Laravel Doc didn't explain how to use this class)

use Illuminate\Pagination\LengthAwarePaginator;

$solved = array();
foreach(Thread::all() as $thread)
{
    if($thread->hasCorrectAnswer())
    {
        array_push($solved, $thread);
    }
}

$results = new LengthAwarePaginator($solved, 11);

This is how to use the regular automatic paginator method

$results = Thread::where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(15)->appends('filter', request('filter'));

My question is: how to use the LengthAwarePaginator and how to add the "orderBy" and "appends" to that manual paginator?

zoldic started a new conversation Confusing "Trying To Get Property Of Non-object" Error

Hi folks, I get this error Trying to get property of non-object

my table migration

public function up()
    {
        Schema::create('replies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('thread_id')->unsigned();
            $table->text('content');
            $table->boolean('correct_answer')->default(0);
            $table->timestamps();
        });
    }

my model file Thread.php

public function hasCorrectAnswer() {
    return $this->replies->where('correct_answer', 1)
        ->first()->correct_answer;
}



public function correctAnswer() {
    return $this->replies->where('correct_answer', 1)
        ->first()->content;
}

my view file

@if($thread->hasCorrectAnswer())
        <div class="item-answer">
          Answer: {{ $thread->correctAnswer() }}
        </div>
@endif

I get the error for "Trying to get property of non-object", and it looks like the problem from @if($thread->hasCorrectAnswer())

I manage to solve it by changing the accessing value using array at hasCorrectAnswer()

public function hasCorrectAnswer() {
    return $this->replies->where('correct_answer', 1)
        ->first()['correct_answer'];  //I change this code
}

public function correctAnswer() {
    return $this->replies->where('correct_answer', 1)
        ->first()->content;  //this code is still the same
}

My question is why I must access the value as array with the hasCorrectAnswer() method and why I still can access the value as obj with correctAnswer() method?

is it because of the @if($thread->hasCorrectAnswer()) and {{ $thread->correctAnswer() }} in my view file?

26 Oct
1 year ago

zoldic started a new conversation AJAX Update Like And Unlike

Hi folks, I have this like and unlike system in my web app

I have managed to make all the back-end work well (creating, deleting the like), but I still have problem with updating my like/unlike button and its count without refreshing my page using AJAX (it has no problem if I refresh it, everthing will load correctly)

my view

<button type="button" data-like="{{ $reply->id }}">
    {{ $reply->isLikedByAuthUser($reply->likes) ? 'unlike' : 'like' }
    <span>{{ $reply->likes->count() }}</span>
</button>

my js

$('[data-like]').on('click', function(e) {
        var self = $(this),
            replyId = self.data('like');

        self.prop('disabled', true);

        $.ajax({
            type: "POST",
            url: urlLike,
            data: {replyId: replyId},
        }).done(function() {
            //what should I add here?
        }).always(function() {
            self.prop('disabled', false);
        });
    });

I want to update my like button without page refresh just like facebook like

if a thread already has 10 likes,

and a user click the like button, it will be 11 likes, so the button will print like this ( unlike (11) ),

if the user change his mind and want to unlike the thread, and he click the button so it will be back to ( like (10) )

What should I add to my AJAX's .done(function() {}

24 Oct
1 year ago

zoldic started a new conversation Admin Delete This

I have solve this I just make a stupid mistake (Admin you can delete this)

18 Oct
1 year ago

zoldic left a reply on Resource Controllers With "Specifying The Resource Model" Problem

Hi, thanks for your reply

sending ['thread' => $thread->id] or ['thread' => $thread], both work just fine.

but I'll just use the ['thread' => $thread->id]

{{ route('threads.store', ['thread' => $thread->id]) }}

and regarding my error ("MethodNotAllowedHttpException"), I made a stupid mistake, in the ThreadController, my update method work just fine

in edit.blade.php, the route('threads.store') is wrong, it is updating not storing, so it should be route('threads.update')

the action is suppose to be {{ route('threads.update', ['thread' => $thread->id]) }}

<form class="form-horizontal" action="{{ route('threads.update', ['thread' => $thread->id]) }}" method="post">
    {{ csrf_field() }}
        {{ method_field('PUT') }}
    //other line of code
</form>

zoldic started a new conversation Resource Controllers With "Specifying The Resource Model" Problem

Hi guys; I made my thread resource controller with the "Specifying The Resource Model"

php artisan make:controller ThreadController --resource --model=Thread

the ThreadController has a slightly differences from the resouce controller without the "Specifying The Resource Model"

php artisan make:controller ThreadController --resource

the difference is in some of the method (show, edit, update, destroy) it has model attach to it for eg. update method

//with "Specifying The Resource Model"
public function update(Request $request, Thread $thread)
    {
        //
    }

//without "Specifying The Resource Model"
public function update(Request $request, $id)
    {
        //
    }

in my edit.blade.php

<form class="form-horizontal" action="{{ route('threads.store', ['thread' => $thread->id]) }}" method="post">
    {{ csrf_field() }}
        {{ method_field('PUT') }}
    //other line of code
</form>

my first question for the data that I send to the route should it be

{{ route('threads.store', ['thread' => $thread->id]) }} or

{{ route('threads.store', ['thread' => $thread]) }}

which one is the correct one to use? (I use the {{ route('threads.store', ['thread' => $thread]) }} for the current of time because of in my route it expect threads/{thread} in the url)

PUT|PATCH | threads/{thread}         | threads.update   | App\Http\Controllers\[email protected]

my second question, I already put the {{ method_field('PUT') }}, but why I get this error ("MethodNotAllowedHttpException") when I try to update my thread

this is my update method in ThreadController, maybe there is an mistake in it

public function update(Request $request, Thread $thread)
    {
        $this->validate($request, [
            'question' => 'required|string|max:50',
            'embed' => 'required|string',
            'description' => 'nullable|string',
        ]);

        $thread->question = $request->question;
        $thread->embed = $request->embed;
        $thread->description = $request->description;
        $thread->slug = str_slug($request->question);
        $thread->save();
        
        Session::flash('status', 'Thread updated!');
        return redirect()->route('threads.index');
    }

zoldic left a reply on Route Resource/CRUD Problem With Slug And Id

Thanks guys, yeah by simply changing the route order, fix the problem

Route::resource('threads', 'ThreadController', ['except' => [
    'show'
]]);
Route::get('/threads/{thread}/{slug}', '[email protected]')->name('threads.show');

zoldic started a new conversation Route Resource/CRUD Problem With Slug And Id

Hi guys,

I made a Resource/CRUD controller for my threads model so there is total 7 route, threads.index, threads.show, etc.

But I made some adjustment to my threads.show route so in the url it has id and slug

Route::get('/threads/{thread}/{slug}', '[email protected]')->name('threads.show');
Route::resource('threads', 'ThreadController', ['except' => [
    'show'
]]);

I have no problem accessing the threads.show route that will show my show.blade.php.

and from that show.blade.php, I have an edit button that should go to my edit.blade.php, when I clicked that edit button the url change from (domain.com/threads/id/slug) to (domain.com/threads/id/edit) but the problem is the route send me back to show.blade.php (not to edit.blade.php).

I manage to solve this by adding id/slug to my threads.edit route

Route::get('/threads/{thread}/{slug}', '[email protected]')->name('threads.show');
Route::get('/threads/{thread}/{slug}/edit', '[email protected]')->name('threads.edit');
Route::resource('threads', 'ThreadController', ['except' => [
    'show','edit'
]]);

it worked, when I press the edit button the route will send me to edit.blade.php.

and this means I must add id/slug to my threads.update and threads.destroy route too

But My question is why is this happening, I just want the id/slug url only for my threads.show route but not for threads.edit, threads.update, threads.destroy

How can I make my threads.edit, threads.update, threads.destroy work without adding an extra id/slug field?

06 Oct
1 year ago

zoldic left a reply on $errors->has('something') With Array

Thanks, it work like a charm

zoldic started a new conversation $errors->has('something') With Array

Hi Guys I'm wondering, is it possible to simplify below code? e.g.

@if ($errors->has('name') || $errors->has('email') || $errors->has('password'))

I tried this code below is not working (make it as an array)

@if ($errors->has(['name', 'email', 'password']) )
27 Sep
1 year ago

zoldic left a reply on How To Redirect Back To Previous Page After Login Success?

protected $redirectTo =  'your-url';

Yes, I understand that line of code but the problem is that code is static, you can only redirect back to your predifined url It can't redirect back to previous page

and I found this solution by Scott Byers, but it is not working too

Laravel >= 5.3 The Auth changes in 5.3 make implementation of this a little easier, and slightly different than 5.2 since the Auth Middleware has been moved to the service container. Modify the new Middleware auth redirector

/app/Http/Middleware/RedirectIfAuthenticated.php

Change the handle function slightly, so it looks like:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/home');
    }

    return $next($request);
}

(Solution) I managed to solve it (but I'm not that sure if this is the correct way to do it) in the AuthenticatesUsers.php file

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        return back(); //add this line of code
    }

and btw I found this RedirectsUsers.php file, but I have no idea how it work so I don't touch it

<?php

namespace Illuminate\Foundation\Auth;

trait RedirectsUsers
{
    /**
     * Get the post register / login redirect path.
     *
     * @return string
     */
    public function redirectPath()
    {
        if (method_exists($this, 'redirectTo')) {
            return $this->redirectTo();
        }

        return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
    }
}
26 Sep
1 year ago

zoldic left a reply on How To Redirect Back To Previous Page After Login Success?

Hi tisuchi, any help man? I still can't figure it out

zoldic left a reply on How To Redirect Back To Previous Page After Login Success?

Hi I have watch this video from Laravel 5.4 From Scratch (But Jeffrey didn't really teach about it)

  • Rapid Authentication and Configuration
  • Associating With Users
  • Associating With Users: Part 2

(I use Lav 5.4) I have check my LoginController.php, but i can't find this line of code

if (Auth::attempt(['email' => $email, 'password' => $password])) {

and I simply put your code to my LoginController.php and it crashed

My LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    
    protected $redirectTo = '/home';
    
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function credentials(Request $request) {
        return $request->only($this->username(), 'password') + ['verified' => true];
    }
}

zoldic left a reply on How To Redirect Back To Previous Page After Login Success?

in the LoginController.php there is a line of code that control this login success redirect protected $redirectTo = '/home';

where should I put this into? what is file name?

return redirect()
        ->back();

and this one, where should I put it? what is the file name?

return redirect()->intended('defaultpage');

zoldic started a new conversation How To Redirect Back To Previous Page After Login Success?

Hi, do you guys know how to redirect back to previous page after login success? There is an answer for it at stackoverflow but I'm kinda confuse about which file he is refering to https://stackoverflow.com/questions/15389833/laravel-redirect-back-to-original-destination-after-login

answered by vFragosop

Simply put,

On auth middleware: (what is the file name he is refering to? RedirectIfAuthenticated.php?)

// redirect the user to "/login"
// and stores the url being accessed on session
if (Auth::guest()) {
    return redirect()->guest('login');
}
return $next($request);

On login action: (same here, what is the file name? LoginController.php?)

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('defaultpage');
}
24 Sep
1 year ago

zoldic left a reply on Differentiate Login & Register Validation Error?

Ok tx, But what is the name of the file that control the error name? because if I simply change the 'email' to 'loginemail' in the login.blade.php, nothing will really happen

@if ($errors->has('loginemail'))
    <span class="help-block">
        <strong>{{ $errors->first('loginemail') }}</strong>
    </span>
@endif 

zoldic started a new conversation Differentiate Login & Register Validation Error?

Hi guys, I notice that both login (login.blade.php) & register (register.blade.php) has the same validation error for email & password

@if ($errors->has('email'))
    <span class="help-block">
        <strong>{{ $errors->first('email') }}</strong>
    </span>
@endif 

since I use both login & register at the same page, I want to differentiate their error for eg. i can keep the register validation error the same

@if ($errors->has('email'))
    <span class="help-block">
        <strong>{{ $errors->first('email') }}</strong>
    </span>
@endif 

while the login validation error should have a different error "loginemail"

@if ($errors->has('loginemail'))
    <span class="help-block">
        <strong>{{ $errors->first('loginemail') }}</strong>
    </span>
@endif 

what file should I change?

21 Aug
1 year ago

zoldic left a reply on Zurb Foundation JS Can't Work In Laravel

Thanks a lot httpix, it work now and I totally forgot to add this too $(document).foundation();

<body>
    @include('partials.topbar')

    <!-- Scripts -->
    <script src="{{ asset('js/vendor/jquery.js') }}"></script>
    <script src="{{ asset('js/vendor/what-input.js') }}"></script>
    <script src="{{ asset('js/vendor/foundation.min.js') }}"></script>
    <script>
      $(document).foundation();
    </script>
</body>  

zoldic started a new conversation Zurb Foundation JS Can't Work In Laravel

Hi guys, I'm using Zurb Foundation for my Laravel project But I face a problem, the foundation css work just fine but the JS just failed to work somehow

I use the complete version of foundation 6 http://foundation.zurb.com/sites/download.html/

I put the both the "CSS" folder (app.css, foundation.min.css) and the "JS" folder (app.js, vendor folder (foundation.min.js, jquery.js, what-input.js) into my "public" folder

Here is my main.blade.php file that load the foundation CSS and JS file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- Styles -->
    <link href="{{ asset('css/foundation.min.css') }}" rel="stylesheet">
</head>

<body>
    @include('partials.topbar')
    <!-- Scripts -->
    <script type="text/javascript" src="{{ asset('js/vendor/foundation.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/vendor/jquery.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/vendor/what-input.js') }}"></script>
</body>
</html>

and here is the topbar.blade.php inside the partials folder original source code (Advanced Layout) http://foundation.zurb.com/sites/docs/top-bar.html

<div class="title-bar" data-responsive-toggle="responsive-menu" data-hide-for="medium">
  <button class="menu-icon" type="button" data-toggle="responsive-menu"></button>
  <div class="title-bar-title">Menu</div>
</div>

<div class="top-bar" id="responsive-menu">
  <div class="top-bar-left">
    <ul class="dropdown menu" data-dropdown-menu>
      <li class="menu-text">Site Title</li>
      <li class="has-submenu">
        <a href="#0">One</a>
        <ul class="submenu menu vertical" data-submenu>
          <li><a href="#0">One</a></li>
          <li><a href="#0">Two</a></li>
          <li><a href="#0">Three</a></li>
        </ul>
      </li>
      <li><a href="#0">Two</a></li>
      <li><a href="#0">Three</a></li>
    </ul>
  </div>
  <div class="top-bar-right">
    <ul class="menu">
      <li><input type="search" placeholder="Search"></li>
      <li><button type="button" class="button">Search</button></li>
    </ul>
  </div>
</div>

The JS script just failed to work, do you guys have any idea how to solve this problem?