larafever

larafever

Member Since 2 Years Ago

Accra

Mobile Applications Developer at PaySwitch Ghana

Experience Points 12,960
Experience Level 3

2,040 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 88
Lessons
Completed
Best Reply Awards 5
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.

28 May
1 month ago

larafever left a reply on Password Reset Link, Incorrect Format And Invalid Token - Laravel 5.7 Multi Language

Route::post('/password/reset', 'Auth\[email protected]')->name('password.reset');

this needs to be refactored to

php
Route::post('/password/reset/{token}', 'Auth\[email protected]')->name('password.reset');

using this way, I presume that password.reset route is in a route group that enforce locale prefixing

php

Route::group(["prefix"=>"en"],function(){

//sub routes here

});

larafever left a reply on I Want If User Register Successfully Then User Will Come Next Time The Registration Will Not Be Show For That User.

If you are implementing the default authentication flow then you can use the guest middleware on the registration route

php

Route::get('/register')->middleware('guest');

or add it in the construct method of the class which has the registration method

27 May
1 month ago

larafever left a reply on Redirect To Other Server After Login

Are you trying redirect to an external url?

return redirect()->out('domain.com');

larafever left a reply on Eloquent Relationship 1 To 1: With() Not Working

Since both tables have column id and id in permission groups table is referenced in permissions table, calling the with method with limited related column should always include the referential column in this case ID in permission groups table

larafever left a reply on Eloquent Relationship 1 To 1: With() Not Working

@SNAPEY - I think it should be

$permission = Permission::with('permission_group:id,name')->get(); instead

02 Jul
2 years ago

larafever left a reply on Rest APIs, Tokens, Angular

Try JWT, https;//jwt.io

26 Mar
2 years ago

larafever left a reply on Display Image

First run the artisan command ~php artisan storage:link

This command is going to create a shortcut of ..\storage\app\public folder in the public folder in your root directory.

Now if you are using Laravel's default filesystem driver then local then you can serve your image using

<img src="{{(url('/storage/uploads/',$user->image))}"/>

if file name may container any url unfriendly characters then use the

<img src="{{ urldecode(url('/storage/uploads/',$user->image))}"/>

MAKE SUE THE UPLOAD FOLDER RESIDE IN THE LARAVEL STORAGE\APP\PUBLIC FOLDER

I think it will work if your path is set right

larafever left a reply on Display Image

Try this

<img src="{{ urldecode(url('/storage/uploads/',$user->image))}"/>

I think it will work if you path is set right

23 Mar
2 years ago

larafever left a reply on I Have Issue In Laravel Random() Query .

Try


$data = User::where('id','!=',5)->inRandomOrder()->take(10)->get();

21 Mar
2 years ago

larafever left a reply on Count Voting Results

Go the model way pal

larafever left a reply on Redirect Does Not Work After Login

Try this


private authenticated($request,$user){
return redirect('/admin');
}
09 Feb
2 years ago

larafever left a reply on Authentication Problem In 5.3

Authenticated user can't called in the __construct() , besides laravel auto check if authenticated already or redirect to login automatically once you add the

public __construct(){
$this->middleware('auth');
}

larafever left a reply on Authentication Problem In 5.3

Authenticated user can't called in the __construct() , besides laravel auto check if authenticated already or redirect to login automatically once you add the ```php public __construct(){ $this->middleware('auth'); }

larafever left a reply on Authentication Problem In 5.3

if you are using the default login controller that uses Illuminate\Foundation\Auth\AuthenticatesUsers then you can use the authenticated method to get the authenticated user where you can assign it to a variable


  protected function authenticated(Request $request, $user){
      $this->user = $user;
    }

07 Feb
2 years ago

larafever left a reply on Eagear Loading Multiple Tables

Try this

$this->menus = UserProfile::with(['permissions' => function ($q) {
      $q->select('id', 'page_name', 'page', 'view', 'submit', 'print', 'user_profiles_id')->first();
   }])->get();

larafever left a reply on Error 500 (Internal Server Error) In Ajax Request

you forgot CSRF-TOKEN field for your ajax request

larafever left a reply on Problem With Eloquent Relations In My Project

try this, your codes are long for digestion,

$tasklist = TaskDetails::with(['type','userList'])->get();

larafever left a reply on Eagear Loading Multiple Tables

try this is more eloquent approach

class Permission extends Model
{
    public function user_profiles()
    {
      return $this->belongsTo('App\UserProfile','user_profiles_id');
// just add second param and this will reference a foreign key column that connects the permissions model and the users profile
    }
}

user

class User extends Model
{
    public function user_profiles()
    {
        return $this->hasOne('App\UserProfile','user_profiles_id','id');
//the relationship should be user has one userprofile using the fk column user_id in the userprofile table and id in the user table
    }
}

userprofile

class UserProfile extends Model
{
    public function users()
    {
        return $this->belongsTo('App\User','user_id');
//relationship is userprofile belongsTo one user, profile cannot be possessed by multiple users
    }

    public function permissions()
    {
      return $this->hasMany('App\Permission','user_profiles_id','id');
    }
}

I don't really know how you want to implement the permissions on users, if users are assign to multiple permission then the above will work fine.

Now eager load

$this->menus = User::select('id', 'username')->with('user_profiles.permissions')->get();

We don't need to do more join join since we have our eloquent relationships but not that all but not $hidden`` columns in bothuser_profilesmodel andpermission``` model will be fetched.. We can hide columns that are irrelevant to most of our queries by using the

class UserProfile extends model{

    protected $hidden = ['your_columns_that_are_irrelevant'];
}

Hope it helps

larafever left a reply on Local Install On Windows

I have been using xampp for a while, currently running php 7.0.13, it is helpful if you are running multiple projects using different frameworks, I start my server on startup and all you need is localhost/path_to_project, and it's even fun with the vhost config where you can have virtual address for every project.. Mamp on windows sucks, 30 days trial and you get stranded

larafever left a reply on Laravel Login Encrypt And Bcrypt Method?

For registration use

bcrypt($your_password)// encrypt password for users

Then use

Auth::attempt(['username'=>$username,'password'=>$password]);
//Laravel automatically Hash check password for logins if you use the Auth::attempt(), and make sure your password column in your db is named password else this will not work
06 Feb
2 years ago

larafever left a reply on Laravel Job

Can't you eager load in the constructor ?


protected $message;

public __constructor(Message::class $message){
$this->message = $message->load(['forum','user']);
}

I think this should work if you inject the Message class as a dependency for that job

05 Feb
2 years ago

larafever left a reply on How To Reference Item In Multi-dimensional Array/collection

Too many codes to digest pal, but i hope you got the out put below, as show above in your explanation...

I think you have to do one more foreach loop in the items, since is array from your explanation

larafever left a reply on Do I Really Need Server Side Validation?

Server side validation should be your last data transfer check ( incoming and outgoing ), you can do checks on request type (ajax and non-ajax ) and act accordingly but make sure there is an ultimate fallback especially for ajax request

25 Jan
2 years ago

larafever left a reply on Override Default Email For Password Resets In 5.4?

Try this in your USER MODEL

public function getEmailForPasswordReset()
{
    return $this->email

}

20 Jan
2 years ago

larafever left a reply on Secure Register Form From Preventing Html Injection

@mbpp then user being changed type to 2 will be validated as 2 type... I think your registration process for both users have a distinct difference in inputs and some similarities, if so then can break your validation down to specific validation rule for specific type ID then use what I illustrated earlier as general validation...

larafever left a reply on Question About Eloquent Model

Can you explain further...?

larafever left a reply on Secure Register Form From Preventing Html Injection

Why don't use the L5.3 validator ... I'm using the same two way user registration method on one controller ...

Just validate the hidden account type, create one model for the account types then do eloquent model relationship like user belongsTo account type model and account type model hasMany users..

In the migration for account types

Id->increments Title->unique

Then in your users table just do

Type_id->integer|unsigned|index Then create FK on type_I'd

So when you validating the form

account_type => 'required|digits:1|exists:account_types,I'd

Use digits to accept only numbers n 1 for string length, so let say 1 or 2 or 3 ... 9 not two digit number. Then the number should exist in account types table under ID column

larafever left a reply on Recieve Email When User Registers

Check this authentication events

laravel.com/docs/5.3/authentication#events

19 Jan
2 years ago

larafever left a reply on Authentication Error

sorry for the formatting I'm having problems with my browser tho

Hope it helps

larafever left a reply on Authentication Error

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
    
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm(){
        return view('auth.login.login');
//return your login view
    }
    
     protected function username(){
        return "username";
//return the column specified as username, the default is email, I used username
    }
    
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|min:6|alpha_dash', 'password' => 'required|min:8',
        ]);

//Validate  the login form, make sure your form inputs has names attributes as specified here, so username input named username should be the same as the keys for validation

larafever left a reply on Authentication Error

Try this and I think you will be fine with the controller

larafever left a reply on Authentication Error

We can do this without copying all the AuthenticatesUsers trait

Try this and I think you will be fine with the controller


<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

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

    /**
     * Create a new controller instance.
     *
     * @return void
     */
%

larafever left a reply on Authentication Error

We can do this without copying all the AuthenticatesUsers trait

Try this and I think you will be fine with the controller

18 Jan
2 years ago

larafever left a reply on How To Remove An Item From A List With Given ID In VueJS

ooh ok... sorry I'm not into FrontEnd tho

larafever left a reply on How To Save Multiple Query Results In One Array?

Sorry for the late reply I was away for work..

let solve the issue of latest post...


//here we want the 5 latest in each category

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->latest()->take(5);
    });

//just use the latest method if you have created_at column in your post table

//if you don't a created_at column in your table we can use the id of the post since it increments for each post we add, just fetch from below to top take the first 5 post

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->order('id','desc')->take(5);
    });

okay let's start with Category::all() this fetch all the categories we have, ->map() is a helper method in that enables you to do iterations on collections. Note that in L5.3 all eloquent models return Collections therefore we can call collections helper methods on them learn more at https://laravel.com/docs/5.3/collections. function($category, $key) is the same as function($item, $key) Since we are iterating on the collection Category::all() we need to get each (in this case let say category in categories) item in the collection. That item at the current iterate is $category or $item and that should be the first parameter in the inner function() the $key is current index of the iterate..

Let's do this quick illustration


//LETS SAY Category::all() return the collection and assigned to $cat below

$cat = {[
        {
            id:1,
            name:"Music"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        },
        {
            id:2,
            name:"Health"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        },
        {
            id:3,
            name:"Entertainment"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        }
    ]};

//then we perform iteration on $cat since we need 5 post for each of this category, we can't use foreach loop straight away since we are working with a  collection, so we use the map() helper method to iterate.

//The map() helper method accepts an anonymous function as a parameter to hold off each iteration process, then return the item of the iteration process and the index of the item.. so in our case we are looking for a category in $cat so I'd pass $category as my item and $key as my index  for the item

 
$cat->map(function($category,$key){

//so in there is where we get post for each category then return it, and since we have an eloquent relationship we don't need to do more query logic here

/*so for the first iterate on $cat

$category = {
            id:1,
            name:"Music"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        };

so we get all post with category_id of 1 , as per our relationship

*/

    return $category->posts->latest()->take(5);

//since we are using the map() helper function, L5.3 automatically do the pushing for each iteration and at the end we get all the latest 5 post for each category.

});


Hope it helps

larafever left a reply on How To Remove An Item From A List With Given ID

Take a look at the DOCS on collection.. You can use the collect method on any array to convert it to collection then use Laravel in built delete method to delete by key...

https://laravel.com/docs/5.3/collections

larafever left a reply on Laravel Sending Mail Not Working On Production Server

@mojemoron .. You are welcome, can you mark my answer as the best answer?

17 Jan
2 years ago

larafever left a reply on Laravel Live Search

The problem I think is returning $results from the Controller..

Try this

return response()->json(['results'=>$result]);

This way you can get the results array as an object in front-end

So in JS you just call

$.ajax().done(function (response){

var results = response.results; });

Sorry for unable to format code, I'm on mobile device...

larafever left a reply on Laravel Sending Mail Not Working On Production Server

MAIL_DRIVER=smtp MAIL_HOST=mail.pearlstack.com MAIL_PORT=587 MAIL_USERNAME=your client username MAIL_PASSWORD=youre client password MAIL_ENCRYPTION=TLS

You check your mail client config from your cpanel or production server

larafever left a reply on How To Save Multiple Query Results In One Array?

okay I think we can create Eloquent Relationship between category model and the post model using category_id so let say on the category model

 
public function posts(){
return $this->hasMany('App\Post','category_id','id');
}

Now you can use the posts method

use App\Category;

//first senario LOAD 5  posts for each category

//use each or map method to do iterations on collections with two param (current item and key of current item ).In our case I use $category as the current item

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->take(5);
    });

//we can do anything with $eachCategoryWith5 variable... I will throw it into a view

return view('categories.summary',compact('eachCategoryWith5');

Then you do multiple foreach in the view since $eachCategoryWith5 a two dimensional array


   @foreach($eachCategoryWith5  as $categoryPost)
            @foreach($catetgoryPost as $post)
            {{$post}}
            @endforeach
     @endforeach

Note that $post will be a collection and therefore syntax like $post->title is acceptable

Hope it helps

07 Jan
2 years ago

larafever left a reply on Redirect After Registration Like Login

@jrdw, I think Laravel do all that trick with events that can be fired or broadcast, what i found in the


..\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php


//This the default laravel register method 
public function register(Request $request)
    {
    //validates the register form
        $this->validator($request->all())->validate();
    
    //attach new registered user event which can be fired or broadcast
        event(new Registered($user = $this->create($request->all())));
    
    //this automatically login users and enables Auth guard after registration
         $this->guard()->login($user);
    
    /*

this is helper that enables your to do anything with register user or return to a specific URL. By default laravel only redirect to auth middleware after registration since  $this->guard()->login($user); enables Auth guard therefore if you want to redirect to LOGIN, it will be impossible because LOGIN is a Guest guard

*/
        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

We can override this method to suit our need and still get what Laravel offers by default without changing anything here.. This is how we do it by overriding Register method in RegisterController.php


..\app\Http\Controllers\Auth\RegisterController.php
//we define our redirectTo
    protected $redirectTo = '/login';

//create a new method that overrides default register 

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

       // $this->guard()->login($user);
    //this commented to avoid register user being auto logged in

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

//we will maintain the default create method but you can tweak it to suit you needs

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

 //we can also play with the registered user object thrown after registration using the registered method because you returned that method or redirectPath method in register method.

protected function registered(Request $request, $user)
    {
        //we can send users account formation email here or anything we want with users even fire that Registered event created earlier

}

Hope it helps

larafever left a reply on How To Return Validation Errors As JSON To View

@MrRobot21, can you embed your code for this method


 respondCreated();

I can suggest this looking at your code logic

//I created a new respondCreated Method

public function respondCreated(message)
    {
     //if you to return message to view or ajax process
     return response()->json(['message'=>message]);
     //Pass message parameter as message object for ajax

     //or anything with message

     
    }

  //add a new lesson to lessons table
    public function store(StoreLessons $request) 
    {
        $validator = Validator::make($data, $rules);
        
        if ($validator->fails()) {
    
    //pass validator errors as errors object for ajax response

          return response()->json(['errors'=>$validator->errors()]);
        }
    
    else{
        Lesson::create($request->all());
    
    // call respondCreated and pass message
        return $this->respondCreated('Lesson created successfully');
    }
    }

Embed your code at line 49 and let's see what's happening

06 Jan
2 years ago

larafever left a reply on Base Directory Of My Website Is Accessible And That Is Public. How To Make It Hid From Public?

Try this tweak, create a .htaccess file in your base website folder, paste this in it, it should solve your problem


Options -Indexes
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

larafever left a reply on How To Return Validation Errors As JSON To View


  //add a new lesson to lessons table
    public function store(StoreLessons $request) 
    {
        $validator = Validator::make($data, $rules);
        
        if ($validator->fails()) {
    
    //pass validator errors as errors object for ajax response

          return response()->json(['errors'=>$validator->errors()]);
        }
    
    else{
        Lesson::create($request->all());
        return $this->respondCreated('Lesson created successfully');
    }
    }

So a client side you can get errors object by:


//after ajax done

$.ajax().done(function(response){
    //check if response has errors object
    if(response.errors){

    // do what you want with errors, 

    }
});

Hope it helps

larafever left a reply on 404 Errors

Go to resource folder

Find views folder check if a subfolder called Errors exist if not create a new one..... This where views for HTTP status codes like 404, 503 and more will be hosted....

Create a new blade file with various error codes as name

Example..

404.blade.php - is a view for 404 page

You can create more Error views Laravel will direct users to those views when those errors occurs.

Read more at https://laravel.com/docs/5.3/errors

larafever left a reply on Show Html In Blade Email

Try this

''' {!! @html_entity_decode($line) !!} '''

larafever left a reply on Get Password Reset Email From Different Model

@martinbean, it's not working... Nothing is happening...