How do I generate pagination links?
My code looks like this:
// In Model
public function comments()
{
return $this->hasMany(Comment::class);
}
// In Controller
public function show(User $user)
{
$user = User::query()
->with(['comments' => fn ($query) => $query->paginate(20)->withQueryString()])
->find($user->id);
return view('user.show', [
'user' => $user,
]);
}
// In blade
#foreach ($user->comments as $comment)
//more
#endforeach
{{ $user->comments->links() }} // not working!
public function show(User $user), followed by $user = User::find($user->id) is completely redundant... You already have $user, and even with the additional stuff, this is still silly; just use $user->load(...) in the future.
But, since you're trying to Paginate comments, just do like so:
public function show(User $user) {
$comments = $user->comments()->paginate(20);
return view('user.show', [
'user' => $user,
'comments' => $comments
]);
}
Then in your view:
#foreach ($comments as $comment)
<!-- ... -->
#endforeach
{{ $comments->links() }}
FOLLOW THIS STEP
1.OPEN YOUR PROJECT
2.Go to Providers
3.Open AppServiceProviders
4.Paste This Code
public function boot()
{
//
Paginator::useBootstrap();
}
Or This Is The Whole Code Of AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
Paginator::useBootstrap();
}
}
Related
I have a small project in which there should be a comment for each post. I tried to do this using the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
use App\Repository\ICommentRepository;
class CommentController extends Controller
{
/**
* Write Your Code..
*
* #return string
*/
public function store(Request $request)
{
$request->validate([
'body'=>'required',
]);
$data = $request->all();
$data['user_id'] = auth()->user()->id;
$this->comment->createComment($data);
return back();
}
}
With the following error
Undefined property: App\Http\Controllers\CommentController::$comment
After a bit of searching, I realized my mistake and corrected it as follows
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
public function __construct(IAdminRepository $comment){
$this->comment = $comment;
}
/**
* Write Your Code..
*
* #return string
**/
public function store(Request $request)
{
$input = $request->all();
$request->validate([
'body'=>'required',
]);
$input['user_id'] = auth()->user()->id;
$this->comment->createPost($input);
return back();
}
}
Then I got the same error as before and it showed me the same code while I was changing the contents of the code
I tried to clear the cache with php artisan config:clear and php artisan optimize but nothing changed.
pleas help me
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
private $comment;
public function __construct(IAdminRepository $comment){
$this->comment = $comment;
}
/**
* Write Your Code..
*
* #return string
**/
public function store(Request $request)
{
$input = $request->all();
$request->validate([
'body'=>'required',
]);
$input['user_id'] = auth()->user()->id;
$this->comment->createPost($input);
return back();
}
}
you did not define the $comment variable and you are trying to assign value to it.
You need to declare variable comment before the line for the constructor.
i.e
private $comment; //this line is important and it was missing in your code
public function __construct(IAdminRepository $comment){
$this->comment = $comment;
}
here is what she need
private $comment;
public function __construct(IAdminRepository $comment){
$this->comment = $comment;
}
if this is not working then you have something wrong in you IAdminRepository class
Here is the source code of Appservice Provider ..when i commented out code inside boot function then laravel send me just a single email of laravel default email verfication template ...but that code inside boot function sending two email instead of one email ..laravel sending custom verfication template but twice
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Config;
use Carbon\Carbon;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
VerifyEmail::toMailUsing(function ($notifiable) {
$verifyUrl = URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
$user = User::whereEmail($notifiable->getEmailForVerification())->first();
return (new MailMessage)
->subject('Verify your email address')
->markdown('emails.verify-email', ['url' => $verifyUrl, 'user' => $user]);
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind('path.public', function() {
return base_path().'/';
});
}
}
When you put a block of codes in AppServiceProvider, it runs for every requests. maybe you run it two times (means you have two requests when you want to execute that). trace your requests from start to end of this process.
Just try to remove
$user->sendEmailVerificationNotification();
From RegisterController.php in registered function
In my case:
Before
protected function registered(Request $request, User $user)
{
if ($user instanceof MustVerifyEmail) {
$user->sendEmailVerificationNotification();
return response()->json(['status' => trans('verification.sent')]);
}
return response()->json($user);
}
After
protected function registered(Request $request, User $user)
{
if ($user instanceof MustVerifyEmail) {
return response()->json(['status' => trans('verification.sent')]);
}
return response()->json($user);
}
I'm trying "laravel-modules" and "Laravel-permission package". But when run post, it has issue 'Method [validate] does not exist.'. i have added 'use Validator;' but no thing change. In some topics, i remove "use Illuminate\Routing\Controller;" in PermissionController, but it have error
Controller
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
My PermissionController
namespace Modules\User\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Auth;
//Importing laravel-permission models
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Session;
class PermissionController extends Controller
{
// use Validator;
public function __construct() {
$this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources
}
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
$permissions = Permission::all(); //Get all permissions
return view('user::permissions/index')->with('permissions', $permissions);
// return view('user::index');
}
/**
* Show the form for creating a new resource.
* #return Response
*/
public function create()
{
$roles = Role::get(); //Get all roles
return view('user::permissions/create')->with('roles', $roles);
}
/**
* Store a newly created resource in storage.
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name'=>'required|max:40',
]);
$name = $request['name'];
$permission = new Permission();
$permission->name = $name;
$roles = $request['roles'];
$permission->save();
if (!empty($request['roles'])) { //If one or more role is selected
foreach ($roles as $role) {
$r = Role::where('id', '=', $role)->firstOrFail(); //Match input role to db record
$permission = Permission::where('name', '=', $name)->first(); //Match input //permission to db record
$r->givePermissionTo($permission);
}
}
return redirect()->route('permissions.index')
->with('flash_message',
'Permission'. $permission->name.' added!');
}
}
Route
Route::group(['middleware' => 'web', 'prefix' => 'permissions', 'namespace' => 'Modules\User\Http\Controllers'], function()
{
Route::get('/', 'PermissionController#index');
Route::get('/create', 'PermissionController#create');
Route::post('/', 'PermissionController#store');
Route::delete('/', ["as" => "permissions.destroy", "uses" => "PermissionController#destroy"]);
});
Add back in use Validator in your PermissionController. Add this right after use Auth;. You have currently added this in the wrong place.
Then change your $this->validate(...) code to:
// validate the input
$validation = Validator::make( $request->all(), [
'name'=>'required|max:40',
]);
// redirect on validation error
if ( $validation->fails() ) {
// change below as required
return \Redirect::back()->withInput()->withErrors( $validation->messages() );
}
I was trying
$this->validate($request, [
'password' => 'required|confirmed|min:6',
]);
But in Laravel 5.7 following code did the trick for me
$request->validate([
'password' => 'required|confirmed|min:6',
]);
I was following the laracasts video for creating follow option but on clicking on the username it is showing the above error and I don't know where to define this variable. Followscontroller
<?php
namespace App\Http\Controllers;
use Redirect;
use App\User;
use Laracasts\Commander\CommanderTrait;
use App\FollowUserCommand;
use Sentinel;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FollowsController extends Controller
{
use CommanderTrait;
/**
* Follow a User
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
$input = array_add(Input::all(), 'user_id', Sentinel::getuser()->id);
$this->execute(FollowUserCommand::class, $input);
return Redirect::back();
}
/**
* Unfollow a User
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
FollowUserCommand
<?php namespace App;
use App\User;
class FollowUserCommand {
public $user_id;
public $userIdToFollow;
function __construct($user_id, $userIdToFollow)
{
$this->user_id = $user_id;
$this->userIdToFollow = $userIdToFollow;
}
}
FollowUserCommandHandler
<?php namespace App;
use Laracasts\Commander\CommandHandler;
class FollowUserCommandHandler implements CommandHandler {
protected $userRepo;
function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}
public function handle($command)
{
$user = $this->userRepo->findById($command->user_id);
$this->userRepo->follow($command->userIdToFollow, $user);
return $user;
}
}
UserRepository
<?php namespace App;
use App\User;
class UserRepository {
public function save(User $user)
{
return $user->save();
}
public function getPaginated($howMany = 4)
{
return User::orderBy('first_name', 'asc')->paginate($howMany);
}
public function findByUsername($username)
{
return User::with(['feeds' => function($query)
{
$query->latest();
}
])->whereUsername($username)->first();
}
public function findById($id)
{
return User::findOrFail($id);
}
public function follow($userIdToFollow, User $user)
{
return $user->follows()->attach($userIdToFollow);
}
}
User.php
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
// This function allows us to get a list of users following us
public function follows()
{
return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}
// Get all users we are following
public function following()
{
return $this->belongsToMany('User', 'followers', 'user_id', 'follow_id')->withTimestamps();
}
// if current user follows another user
public function isFollowedBy(User $otherUser)
{
$idsWhoOtherUserFollows = $otherUser->follows()->lists('followed_id');
return in_array($this->id, $idsWhoOtherUserFollows) ;
}
}
form.blade.php
#if($user->isFollowedBy($currentUser))
<p>You are following {{ $user->username }}<p>
#else
{!! Form::open(['route' => 'follows_path']) !!}
{!! Form::hidden('userIdToFollow', $user->id) !!}
<button type="submit" class="btn btn-primary">Follow {{ $user->username }} </button>
{!! Form::close() !!}
#endif
Assuming the tutorial implements the Auth class, you can get the current user by changing #if($user->isFollowedBy($currentUser)) to #if($user->isFollowedBy(\Illuminate\Support\Facades\Auth::user())). It is otherwise very difficult to read through your code, but kudos to you for trying to be thorough.
You obviously don't want to use Auth::user() in this way. Trying using it as Auth::user() without the full namespace, but otherwise add the namespace as use Illuminate\Support\Facades\Auth; in the controller handling that view.
I am struggling to understand how laravel works and I have a very difficult time with it
Model - User.php the User model
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('email' , 'username' , 'password', 'code');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function Characters()
{
return $this->hasMany('Character');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Model - Character.php the character model
<?php
class Character extends Eloquent {
protected $table = 'characters';
protected $fillable = array('lord_id','char_name', 'char_dynasty', 'picture');
public function user()
{
return $this->belongsTo('User');
}
public function Titles()
{
return $this->hasMany('Title');
}
}
?>
routes.php
Route::group(array('prefix' => 'user'), function()
{
Route::get("/{user}", array(
'as' => 'user-profile',
'uses' => 'ProfileController#user'));
});
ProfileController.php
<?php
class ProfileController extends BaseController{
public function user($user) {
$user = User::where('username', '=', Session::get('theuser') );
$char = DB::table('characters')
->join('users', function($join)
{
$join->on('users.id', '=', 'characters.user_id')
->where('characters.id', '=', 'characters.lord_id');
})
->get();
if($user->count()) {
$user = $user->first();
return View::make('layout.profile')
->with('user', $user)
->with('char', $char);
}
return App::abort(404);
}
}
In my code I will redirect to this route with the following:
return Redirect::route('user-profile', Session::get('theuser'));
In the view I just want to do:
Welcome back, {{ $user->username }}, your main character is {{ $char->char_name }}
My problem is that I will receive this error: Trying to get property of non-object in my view. I am sure it is referring to $char->char_name. What's going wrong? I have a very difficult time understanding Laravel. I don't know why. Thanks in advance!
You should be using the Auth class to get the session information for the logged in user.
$user = Auth::user();
$welcome_message = "Welcome back, $user->username, your main character is $user->Character->char_name";
You don't need to pass anything to that route either. Simply check if the user is logged in then retrieve the data. You have access to this data from anywhere in your application.
if (Auth::check())
{
//the user is logged in
$user = Auth::user();
To answer your question in the comments, reading the documentation would solve all of these problems, however:
public function user()
{
if (Auth::check())
{
$user = Auth::user();
return View::make('rtfm', compact('user'));
}
else
{
return "The documentation explains all of this very clearly.";
}
}