Member Since 10 Months Ago
410 experience to go until the next level!
In case you were wondering, you earn Laracasts experience when you:
Earned once you have completed your first Laracasts lesson.
Earned once you have earned your first 1000 experience points.
Earned when you have been with Laracasts for 1 year.
Earned when you have been with Laracasts for 2 years.
Earned when you have been with Laracasts for 3 years.
Earned when you have been with Laracasts for 4 years.
Earned when you have been with Laracasts for 5 years.
Earned when at least one Laracasts series has been fully completed.
Earned after your first post on the Laracasts forum.
Earned once 100 Laracasts lessons have been completed.
Earned once you receive your first "Best Reply" award on the Laracasts forum.
Earned if you are a paying Laracasts subscriber.
Earned if you have a lifetime subscription to Laracasts.
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.
Earned once you have achieved 500 forum replies.
Earned once your experience points passes 100,000.
Earned once your experience points hits 10,000.
Earned once 1000 Laracasts lessons have been completed.
Earned once your "Best Reply" award count is 100 or more.
Earned once your experience points passes 1 million.
Earned once your experience points ranks in the top 50 of all Laracasts users.
Earned once your experience points ranks in the top 10 of all Laracasts users.
Started a new Conversation Retrieve Only Some Value From Collection Of Models
Hi, I have a post with a hasMany relation with likes.
In my view I want to call foreach posts:
$post->getCountLikes()
in my Post model I have
public function getCountLikes()
{
$likesForThis = $this->likes;
}
Now i get a Collection with 4 Like objects, but I want to take only the objects with liked column true.
Some helps?
ty
Started a new Conversation Access To Numbers Of Likes For A Specific Tweet.
Hi, I have a Tweet Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User;
use App\Models\Like;
class Tweet extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
}
The User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Tweet;
use App\Http\Traits\Followable;
class User extends Authenticatable
{
use HasFactory, Notifiable, Followable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'slug',
'avatar',
'profile_cover',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'slug',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function timeline()
{
$ids = $this->follows->pluck('id');
$ids->push($this->id);
return Tweet::whereIn('user_id', $ids)->latest()->get();
}
public function tweets()
{
return $this->hasMany(Tweet::class);
}
public function toProfile()
{
return route('profile', $this->slug);
}
public function showAvatar()
{
if ($this->avatar != '/images/avatar.png') {
return '/storage/' . $this->avatar;
}
return $this->avatar;
}
public function showProfileCover()
{
if ($this->profile_cover != '/images/default-profile-cover.jpg') {
return '/storage/' . $this->profile_cover;
}
return $this->profile_cover;
}
public function likes()
{
return $this->hasMany(Like::class);
}
}
And Like Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function tweet()
{
return $this->belongsTo(Tweet::class);
}
}
My Like table is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('tweet_id');
$table->boolean('liked'); // 0 for dislike, 1 for like
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('tweet_id')
->references('id')
->on('tweets')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}
I need to access in my view on $tweet->likes number, how can I?
TY
Started a new Conversation File Storage Folders And Paths
Hi, why for the avatar the system make folder 'avatars' and change the path but for the profile_cover not?
public function update(Request $request, User $user)
{
$validated = $request->validate(
[
"name" => "required|max:255",
"avatar" => [Rule::requiredIf($user->avatar === null)],
"profile_cover" => [Rule::requiredIf($user->profile_cover === null)],
"password" => ["required", "min:8", "max:255", "confirmed"],
]
);
if ($request->hasFile('avatar')) {
$validated['avatar'] = $request->file('avatar')->store('avatars', 'public');
}
if ($request->hasFile('pofile_cover')) {
$validated['profile_cover'] = $request->file('profile_cover')->store('covers', 'public');
}
$validated['slug'] = Str::slug($request['name']);
$validated['password'] = Hash::make($validated['password']);
$user->update($validated);
return redirect($user->toProfile());
}
Awarded Best Reply on File Storage
I found the solution:
Before the image is saved, it's important assign the new path with the store method.
$validated['avatar'] = $request->file('avatar')->store('avatars', 'public');
And after all can be assigned by mass assignment.
Replied to File Storage
I found the solution:
Before the image is saved, it's important assign the new path with the store method.
$validated['avatar'] = $request->file('avatar')->store('avatars', 'public');
And after all can be assigned by mass assignment.
Replied to File Storage
Actually the path showed is :
/storage/private/var/folders/kx/30_xckkd6bvg1h5lbc0ncwvc0000gn/T/php25tMsU
In the table the avatar column is:
/private/var/folders/kx/30_xckkd6bvg1h5lbc0ncwvc0000gn/T/php25tMsU
the view is:
<x-app-layout>
{{-- <x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot> --}}
<div class="lg:flex lg:justify-between max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
<div class="lg:w-1/6">
<x-sidebar></x-sidebar>
</div>
<div class="lg:flex-1 lg:mx-10" style="max-width: 700px">
<header class="relative">
<div class="h-60 rounded-lg mb-3" style="background: lightblue url('{{$user->profile_cover}}') no-repeat center; "></div>
<div class="flex justify-between p-3 items-center">
<div>
<h3 class="font-bold text-2xl">{{$user->name}}</h3>
<p class="text-sm">Joined {{$user->created_at->diffForHumans()}}</p>
</div>
<div>
@if (Auth::id() != $user->id)
<form action="{{route('toggle', $user->slug)}}" method="POST">
@csrf
<button class="bg-blue-500 rounded-xl text-white px-4 py-2 shadow" type="submit">{{Auth::user()->following($user) ? 'Unfollow' : 'Follow'}}</button>
</form>
@else
<form action="{{route('edit-profile', $user->slug)}}" method="GET">
<button class="bg-blue-500 rounded-xl text-white px-4 py-2 shadow" type="submit">Edit profile</button>
</form>
@endif
</div>
</div>
<img class="rounded-full w-32 absolute border-8 border-white" src="/storage{{$user->avatar}}" alt="{{$user->name}} avatar" style="top: 50%; left: calc(50% - 4rem);">
</header>
<div class="border border-gray-300 rounded-lg mt-6 py-4">
<x-timeline :tweets="$tweets"></x-timeline>
</div>
</div>
<div class="lg:w-44 bg-blue-100 rounded-lg p-4">
<x-followings></x-followings>
</div>
</div>
</x-app-layout>
Replied to File Storage
The image don't load, in the src:
http://127.0.0.1:8000/private/var/folders/kx/30_xckkd6bvg1h5lbc0ncwvc0000gn/T/php3iHLSo
Started a new Conversation File Storage
Hi, I'm trying to upload an avatar for the user and save it with local storage, but I don't understand how. I make this validation:
public function update(Request $request, User $user)
{
$validated = $request->validate(
[
"name" => "required|max:255",
"avatar" => [Rule::requiredIf($user->avatar === null)],
"password" => ["required", "min:8", "max:255", "confirmed"],
]
);
$validated['slug'] = Str::slug($request['name']);
$validated['password'] = Hash::make($validated['password']);
if ($validated['avatar']) {
$validated['avatar']->store('avatars');
}
$user->update($validated);
return redirect($user->toProfile());
}
In my users table I have actually one default avatar:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('avatar')->default('/images/avatar.png');
});
}
After the uplload of new avatar in the user column:
/private/var/folders/kx/30_xckkd6bvg1h5lbc0ncwvc0000gn/T/php7dz4vF
I make the storage link, now how can i retrieve this avatar? and how can i show the storage avatar only if is updated?
ty
Started a new Conversation Controller Does Not Exist
Hi I have this view:
<form action="{{route('toggle', $user->slug)}}" method="POST">
@csrf
<button class="bg-blue-500 rounded-xl text-white px-4 py-2 shadow" type="submit"> {{Auth::user()->following($user) ? 'Unfollow' : 'Follow'}}</button>
</form>
and this route:
Route::post('profile/{user:slug}/follow', [FollowsController::class, 'toggle'])->name('toggle');
I have created the controller but the system return:
Target class [FollowsController] does not exist.
Someone can help me?
Awarded Best Reply on Laravel 6 From Scratch Lesson 62
Solved! Before I was using
use App\Models\User;
Next I changed it with
use Illuminate\Foundation\Auth\User;
Replied to Laravel 6 From Scratch Lesson 62
Solved! Before I was using
use App\Models\User;
Next I changed it with
use Illuminate\Foundation\Auth\User;
Replied to Laravel 6 From Scratch Lesson 62
It looks different because I making the project on Laravel 8
Replied to Laravel 6 From Scratch Lesson 62
At first I go to the profile view:
Route::get('profile/{user:slug}', [ProfileController::class, 'show'])->name('profile');
Next I search for a Tweets of that user and I pass a list of tweets and a user istance.
public function show(User $user)
{
$tweets = Tweet::where('user_id', $user->id)->latest()->get();
return view('profile', ['tweets' => $tweets, 'user' => $user]);
}
In this view I have a button for check if current user follows o not the profile:
<button class="bg-blue-500 rounded-xl text-white px-4 py-2 shadow" type="submit">{{auth()->user()->following($user) ? 'Unfollow' : 'Follow'}}</button>
In the method following I have:
public function following(User $user)
{
return $this->follows->contains($user);
}
When I reload return:
App\Models\User::following(): Argument #1 ($user) must be of type App\Models\User, Illuminate\Foundation\Auth\User given
Started a new Conversation Laravel 6 From Scratch Lesson 62
Hi, I'm doing the final project of laravel 6 from scratch and in the lesson 62 when I pass a $user
variable to the auth()->user()->following($user)
method the system return App\Models\User::following(): Argument #1 ($user) must be of type App\Models\User, Illuminate\Foundation\Auth\User given.
Someone help me pls?
Replied to Foreach Invalid Argument
I solved the problem in this way:
<?php
namespace App\Http\Controllers;
use App\Models\Tweet;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(User $user)
{
$tweets = Tweet::where('user_id', $user->id)->latest()->get();
return view('profile', ['tweets' => $tweets, 'user' => $user]);
}
}
But I don't understand why if I send the only user the system don't send anyway the relationship
Replied to Foreach Invalid Argument
This is were the code works:
<x-app-layout>
{{-- <x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot> --}}
<div class="lg:flex lg:justify-between max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
<div class="lg:w-1/6">
<x-sidebar>
<li><a class="font-bold text-lg mb-4 block" href="{{route('home')}}">Home</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Explore</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Notifications</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Messages</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Bookmarks</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Lists</a></li>
<li><a class="font-bold text-lg mb-4 block" href="{{route('profile', auth()->user()->slug)}}">Profile</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">More</a></li>
</x-sidebar>
</div>
<div class="lg:flex-1 lg:mx-10" style="max-width: 700px">
<div>
<x-tweet-form></x-tweet-form>
</div>
<div class="border border-gray-300 rounded-lg mt-6 py-4">
@foreach ($tweets as $tweet)
<x-timeline :tweet="$tweet"></x-timeline>
@endforeach
</div>
</div>
<div class="lg:w-44 bg-blue-100 rounded-lg p-4">
<x-followings></x-followings>
</div>
</div>
</x-app-layout>
This is the Controller for thath view:
<?php
namespace App\Http\Controllers;
use App\Models\Tweet;
use Illuminate\Http\Request;
class TweetsController extends Controller
{
public function index()
{
return view('home', ['tweets' => auth()->user()->timeline()]);
}
public function store(Request $request)
{
$validated = $request->validate(
[
"body" => "required|max:255"
]
);
Tweet::create([
'user_id' => auth()->user()->id,
'body' => $validated['body'],
]);
return redirect(route('home'));
}
}
this is the profile page where I want to show a user profile with his published tweets:
<x-app-layout>
{{-- <x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot> --}}
<div class="lg:flex lg:justify-between max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
<div class="lg:w-1/6">
<x-sidebar>
<li><a class="font-bold text-lg mb-4 block" href="{{route('home')}}">Home</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Explore</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Notifications</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Messages</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Bookmarks</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">Lists</a></li>
<li><a class="font-bold text-lg mb-4 block" href="{{route('profile', auth()->user()->slug)}}">Profile</a></li>
<li><a class="font-bold text-lg mb-4 block" href="#">More</a></li>
</x-sidebar>
</div>
<div class="lg:flex-1 lg:mx-10" style="max-width: 700px">
<header class="rounded-lg">
<img src="" alt="profile banner of {{$user->name}}">
</header>
<div class="border border-gray-300 rounded-lg mt-6 py-4">
@foreach ($user->tweets as $tweet)
<x-timeline :tweet="$tweet"></x-timeline>
@endforeach
</div>
</div>
<div class="lg:w-44 bg-blue-100 rounded-lg p-4">
<x-followings></x-followings>
</div>
</div>
</x-app-layout>
This is the controller of profile page:
<?php
namespace App\Http\Controllers;
use App\Models\Tweet;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile', ['user' => $user]);
}
}
This is a routes file:
<?php
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TweetsController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth'])->group(function(){
Route::get('/tweets', [TweetsController::class, 'index'])->name('home');
Route::post('/tweets', [TweetsController::class, 'store'])->name('tweet-store');
Route::get('profile/{user:slug}', [ProfileController::class, 'show'])->name('profile');
});
require __DIR__.'/auth.php';
This is User model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Tweet;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function timeline()
{
// Dell'utente attualmente loggato prendo gli id degli utenti che segue
$ids = $this->follows->pluck('id');
// alla collection che mi viene aggiungo l'id dell'attuale utente loggato.
$ids->push($this->id);
// richiamo tutti i tweets che hanno gli ids
return Tweet::whereIn('user_id', $ids)->latest()->get();
}
public function tweets()
{
return $this->hasMany(Tweet::class);
}
public function follow(User $user)
{
return $this->follows()->save($user);
}
public function follows()
{
return $this->belongsToMany(User::class, 'follows', 'user_id', 'following_user_id');
}
}
This is the error:
foreach() argument must be of type array|object, null given
Replied to Foreach Invalid Argument
In this case from a bar of following users I want to click on the user and see his profile.
Replied to Foreach Invalid Argument
In others views I can call:
{{ auth()->user()->tweets }}
And it works, but in this case not
Replied to Foreach Invalid Argument
this is all the user model:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Tweet;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function timeline()
{
// Dell'utente attualmente loggato prendo gli id degli utenti che segue
$ids = $this->follows->pluck('id');
// alla collection che mi viene aggiungo l'id dell'attuale utente loggato.
$ids->push($this->id);
// richiamo tutti i tweets che hanno gli ids
return Tweet::whereIn('user_id', $ids)->latest()->get();
}
public function tweets()
{
return $this->hasMany(Tweet::class);
}
public function follow(User $user)
{
return $this->follows()->save($user);
}
public function follows()
{
return $this->belongsToMany(User::class, 'follows', 'user_id', 'following_user_id');
}
}
Replied to Foreach Invalid Argument
@foreach ($user->tweets as $tweet)
<x-timeline :tweet="$tweet"></x-timeline>
@endforeach
Because I have a relation beetwen users and tweets
public function tweets()
{
return $this->hasMany(Tweet::class);
}
Replied to Foreach Invalid Argument
This is my code:
<a href="{{route('profile', auth()->user()->slug)}}">Profile</a>
Route::get('/profile/{user:slug}', [ProfileController::class, 'show']);
public function show(User $user)
{
return view('profile', ['user' => $user]);
}
Replied to Foreach Invalid Argument
Hi, this is my code:
<a href="{{route('profile', auth()->user()->slug)}}">Profile</a>
Route::get('/profile/{user:slug}', [ProfileController::class, 'show']);
public function show(User $user)
{
return view('profile', ['user' => $user]);
}
Started a new Conversation Foreach Invalid Argument
Hi, I have a route get thath checks and query a slug column in user table. In my controller I have a User $user argument and i return a view with [‘user’ => $user] variable. In the view I have a foreach in which I pass the variable but the system return invalid argument. Some helps?
Replied to Format Uri After Route Model Binding
I make the modifies, now in my controller arrive a right user by slug, but when I send the user to the view: ['user' => $user] In the view at @foreach ($user->tweets as $tweet) The system return Invalid foreach argument, aspect array|object passed null
Replied to Format Uri After Route Model Binding
OK I tried to send the name after that in this way: route('profile', Str::slug($user->name)) But when the controller tries to do the query it doesn't find it results in something in the databaset doesn't match
Replied to Format Uri After Route Model Binding
Sorry let me explain.. At the moment when I click the link the get variable is:" Name Surname". I want to format the variable into:" name-surname" . To keep more user friendly
Started a new Conversation Format Uri After Route Model Binding
Hi, I send a user->name to get route:
<a href="{{route('profile', $user->name)}}">
<p class="text-sm">{{$user->name}}</p>
</a>
After that i bind a user model to the wildcard and query for a name:
Route::get('profile/{user:name}', [ProfileController::class, 'show'])->name('profile');
After all I would like to format the uri in this way name-of-user.
How can I do this?
Commented on Expanding The Timeline
How I can access to the avatar of each one user. At the moment in the timeline I got only the avatar of current logged in user
Started a new Conversation Pass Variable To Component Blade
Hi, why in this code return $tweet is undefined??
<div class="border border-gray-300 rounded-lg mt-6 py-4">
@foreach ($tweets as $tweet)
<x-tweet></x-tweet>
@endforeach
</div>
Replied to Keep Track Of A Subscription Monthly
ok thanks, so i need two additionals columns in the users table for starting and ending the sub?
Replied to Keep Track Of A Subscription Monthly
Spark is very good service but I would like to make it simple.
Started a new Conversation Keep Track Of A Subscription Monthly
Hi, I have one table for some subscriptions plans for users. When the user chose the subscription I want to display the date of subscription and the expiration date, Any suggests?
Thanks!