bbmrw

Member Since 10 Months Ago

Experience Points
1,080
Total
Experience

3,920 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
0
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

  • Community Pillar

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

Level 1
1,080 XP
Dec
17
1 month ago
Activity icon

Replied to Problem With Storing Duplicate Values In Database With Polymorphic Relations In Laravel

I don't have image_users table. I have favorites table and post images table. user_id I have in favorites table.

Activity icon

Replied to Problem With Storing Duplicate Values In Database With Polymorphic Relations In Laravel

Can you show me an example? I am not sure how to make the combination, what exactly do you mean?

Activity icon

Started a new Conversation Problem With Storing Duplicate Values In Database With Polymorphic Relations In Laravel

I have favorites functionality with polymorphic one to many relations in Laravel. I have ProfileImages, PostImages and Favorites models as well as those three tables. When for example I store post image with id 1 in favorites table it looks like this

id   user_id   favoritable_id   favoritable_type
1       15           1          App\Models\PostImage

(favoritable_id is id of post image in post_images table)

And then if I go and store another post image with the id 1, my code as it is, will return message "You already favorited this post image!" but it will store that in favorites table regardless and I need it not to. I need some way to check both favoritable_id and favoritable_type to be unique together in order this to work. If only one of them is unique and other ins't it won't work as it should. I got favoritable_id to be like that, but I can't figure out favoritable_type (I get null value). I tried this way if someone can help me or if there is some other way any help would be appreciated. Here is my code.

web.php

Route::post('/post/image/{postimage}/favorite', [\App\Http\Controllers\FavoritesController::class, 'postImageFavorite'])->name('post-image-favorite');

Controller

public function postImageFavorite(FavoriteRequest $request, PostImage $image, $postimage)
{
	if($request->favorite == true) {
		if(PostImage::where('id', $postimage)->first()) {
		    $favorite = new Favorite();
	    	$favorite->user_id = $request->user()->id;
		    $favorite->favoritable_type	 = $image->getMorphClass();
		    $favorite->favoritable_id	 = $postimage;
		    $favorite->save(); 

		    // HERE IS CODE FOR DUPLICATE, THAT I TRIED
		    $checkForDuplicate1 = Favorite::where('favoritable_id', $postimage)->exists();
		    $checkForDuplicate2 = Favorite::where('favoritable_type', $favorite->favoritable_type)->exists();
		    if($checkForDuplicate1 && $checkForDuplicate2) {
				return response()->json([
			    	'message' => 'You already favorited this post image!'
				]);
		    }
		    
		     	
	    } else {
	    	return response()->json([
			    'message' => 'Post image doesn\'t exist!'
			]);
	    }

		$user = Auth::user();
        $model = Favorite::find($favorite->id);
		$id = $model->favoritable->post->user_profile_id;
        $other_user = User::findOrFail($id);
        $other_user->notify(new NewPostImageFavorite($user));

    } elseif($request->favorite == false) {
		$result = Favorite::where('user_id', auth()->user()->id)
            ->where('favoritable_id', $postimage)
            ->delete();

		return $result;
    }

    return response()->noContent();
}

PostImage.php

public function favorites()
{
    return $this->morphMany(Favorite::class, 'favoritable');
}

Favorites.php

public function favoritable()
{
	return $this->morphTo();
}
Dec
16
1 month ago
Activity icon

Started a new Conversation Problem With Restoring Deleted Notification In Laravel

I am trying to restore deleted notification using Laravel Notification. Problem I am having is that I get error

Call to undefined method Illuminate\Notifications\Notification::withTrashed()

because Notification model is in vendor folder and I can't change it. So I need some workaround for that in order for withTrashed method to be available in Notification model. Any help is appreciated. Here is my code.

Controller

public function restoreDeletedNotification(Request $request)
{
    $restore = Notification::withTrashed()->where('id', $request['id'])->restore();

    return response()->noContent();
}

web.php

Route::post('/notifications/restore', [\App\Http\Controllers\NotificationController::class, 'restoreDeletedNotification'])->name('restore-notification');
Activity icon

Started a new Conversation Problem With Favorites Functionality In Laravel

I am building favorites functionality where user can favorite certain image. I am using cybercog/laravel-love package. The error I am getting in postman when I try to favorite some image is

"message": "Reactant not exists.",
"exception": "Cog\Contracts\Love\Reactant\Exceptions\ReactantInvalid",

I built the same functionality for like posts and it works fine but when I add favorite functionality I get this error. Also when I dd() it breaks in ReactionService.php on line where I put this code,

if($reacterFacade->hasReactedTo($reactant, $reactionType)) {

because $reactant doesn't exist.

Any help is appreciated. Here is my code.

Controller

public function profileImageFavorite(FavoriteRequest $request, ReactionService $reactionService, ProfileImage $profileImage)
{
    $user = Auth::user();
    $reactionService->favorite($user->profile, $profileImage, $request->favorite);

    return new ProfileImageResource($profileImage);
}

ReactionService.php

public function favorite($reacter, $reactant, $favorite)
{
    $reactionType = 'Favorite';
    $reacterFacade = $reacter->viaLoveReacter();
    if ($favorite == true) {
        if ($reacterFacade->hasReactedTo($reactant, $reactionType)) {

            dd('HERE IT BREAKS AND SHOWS ERROR');

            throw ValidationException::withMessages(['profileImage' => 'You already favorited this image']);
        } else {
            $reacterFacade->reactTo($reactant, $reactionType);
        }
    } else {
        if ($reacterFacade->hasNotReactedTo($reactant, $reactionType)) {
            throw ValidationException::withMessages(['profileImage' => 'You did not favorite this image']);
        } else {
            $reacterFacade->unreactTo($reactant, $reactionType);
        }
    }
}

ProfileImage.php

<?php

namespace App\Models;

use Cog\Contracts\Love\Reactable\Models\Reactable as ReactableInterface;
use Cog\Laravel\Love\Reactable\Models\Traits\Reactable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class ProfileImage extends Model implements ReactableInterface
{
    use HasFactory, Reactable, Notifiable;

    protected $fillable = [
        'id',
        'user_profile_id',
        'title',
        'path',
        'url',
        'image_type',
        'love_reactant_id',
    ];
}

migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddLoveReactantIdToProfileImagesTable extends Migration
{
    public function up(): void
    {
        Schema::table('profile_images', function (Blueprint $table) {
            $table->unsignedBigInteger('love_reactant_id')->nullable();

            $table
                ->foreign('love_reactant_id')
                ->references('id')
                ->on('love_reactants');
        });
    }

    public function down(): void
    {
        Schema::table('profile_images', function (Blueprint $table) {
            $table->dropForeign(['love_reactant_id']);
            $table->dropColumn('love_reactant_id');
        });
    }
}

And also I have 'like' functionality for posts with the same code, just changed to be for post and like and it works fine.

Dec
14
1 month ago
Activity icon

Started a new Conversation Problem With Chaining Relationships In Laravel

I have three models and relationships. Post, UserProfile, User. I need to fetch name column value from users table but I need to go through posts and user profile to fetch it. Posts are connected to user profile and user profile is connected to users. I tried $post->userProfile()->user()->name but it won't work. I get error

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::user()

Here is my code. Any help is appreciated.

Post.php

posts table has user_profile_id column

public function userProfile()
{
    return $this->belongsTo(UserProfile::class);
}

UserProfile.php

public function user()
{
    return $this->belongsTo(User::class, 'id');
}

public function posts()
{
    return $this->hasMany(Post::class);
}

User.php

public function profile()
{
    return $this->hasOne(UserProfile::class, 'id');
}
Dec
10
1 month ago
Activity icon

Started a new Conversation How To Make Regular Expression That Will Fetch Username From Database That Has Two Or More Separated Words?

I am making mention notification functionality in Laravel. When some user is typing comment he can mention other user (with @) and then that user will receive notification that he/she is mentioned. Currently I am able to do that, but I have problem if the user has username in database with two or more separated words, then my regular expression that I have doesn't work, it fetches only first word after @ sign. I need help on how to write that regular expression. Any help is appeciated. Here is my code.

Controller

public function store(StorePostComment $request, Post $post, PostComment $postComment = null)
{   
    $pc = new PostComment();
    $pc->text = $request->text;
    $pc->parent()->associate($postComment);
    $pc->post()->associate($post);
    $pc->userProfile()->associate(\Auth::user()->profile);
    $pc->save();

    preg_match_all('/\@([^\s\.]+)/', $pc->text, $matches);  // HERE IS THAT REGULAR EXPRESSION
    $names = $matches[1];

    foreach ($names as $name) {
        $username = User::whereName($name)->first();

        if ($username) {
            $username->notify(new YouAreMentioned($pc));
        }
    }

    return new PostCommentResource($pc);

}
Nov
30
1 month ago
Activity icon

Started a new Conversation Problem With Refactoring Form Validation In Form Request In Laravel

I have some validation rules that I am trying to refactor to be in form request instead of in controller. I am building three step form. In the second post method I have problem. I the beggining of the method I call session questionnaire that has some data from first form, and after that I need to validate data from second form. With current code I get undefined variable questionnaire error because I use that variable in form request. I need help on how to pass that variable from form request to controller in order to work. Any help is appreciated. Here is my code.

Nov
27
1 month ago
Activity icon

Started a new Conversation Problem With Validating Data In Form Request In Laravel

I have a form in Laravel blade and I am having trouble with validating data. I validated data from my controller with $request->validate(['some_data' => 'some_value']) as an example. I put that in variable $validatedData and I use that variable bellow in session put method and in fill method and it worked fine. What I did is tried to refactor code and I put that validation in FormRequest and removed variable $validatedData and put $request instead of it. When I did that then it showed error

Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must be of the type array, object given

and it breaks down because now $request now isn't array like it was before, it is object instead. How should I fix that to work. Any help is appreciated

Aug
07
5 months ago
Activity icon

Replied to How To Validate Password To Check If It Is The Same Password As In Database?

@msslgomez Thanks, but I did have this and for some reason it wouldn't show errors in this project so I decided to do a custom login.

Activity icon

Replied to How To Validate Password To Check If It Is The Same Password As In Database?

@msslgomez

I am having trouble with displaying errors and I couldn't find the solution so custom login it is.

Activity icon

Started a new Conversation How To Validate Password To Check If It Is The Same Password As In Database?

I have login form in Laravel that uses email and password to log on site. I have all validation and everything works fine except for password. When I type wrong password it goes to blank page and I want to write some error beneath password field. I looked in same:password validation but it doesn't work. Any help is appreciated. Here is my code.

LoginController.php

public function login(Request $request)
{
    $rules = [
        'email'    => 'required|email|exists:App\User,email', 
        'password' => 'required|alphaNum|min:5'
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        $request->session()->put('data', $request->input());
        return redirect()->route('login')
            ->withErrors($validator->errors())
            ->withInput($request->session()->put('data', $request->input()));
    } else {
        $userData = array(
            'email'     => $request->get('email'),
            'password'  => $request->get('password')
        );
    }
    
    if (Auth::attempt($userData)) {
        return redirect()->route('dashboard');
    } else {        
        redirect()->route('login');
    }
}
Activity icon

Started a new Conversation Validation Errors Not Showing On Form In Laravel

I have login form in Laravel that works, it can login, logout and also it doesn't pass in aplication if the email or password are incorrect/empty, but it doesn't show any errors on form or in response in network tab. I am using laravel version 7.19.1. and laravel/ui package. Any help is appreciated. Here is my code.

web.php

Route::post('/login', 'Auth\[email protected]')->name('login'); or Auth::routes() either works.

LoginController.php

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
        
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
}

login.blade.php

<div class="login-page">
    <div class="login-box">
        <div class="card mb-0">
            <div class="card-body login-card-body">
                <form method="POST" class="mb-4" action="{{route('login') }}">
                    @csrf
                    <div class="input-group mb-3">
                        <input id="email" type="email" placeholder="Email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" autocomplete="email" autofocus>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-user"></span>
                            </div>
                        </div>
                        @error('email')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="input-group mb-3">
                        <input id="password" type="password" placeholder="Password" class="form-control @error('password') is-invalid @enderror" name="password" autocomplete="current-password">
                        @error('password')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="float-right">
                        <button type="submit" class="btn btn-primary btn-block font-weight-bold">Sign in</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
Aug
05
5 months ago
Activity icon

Started a new Conversation How To Return All Content From Three Variables In One Function In Laravel?

I have three variables articles, users and matches inside one function. I want to be able when I call that function it lists all content from those three variables. Currently when I dd() any variable I get content but I want when function is called to get content from all three. Any help is appreciated. Here is my code.

web.php

Route::get('/dashboard', '[email protected]')->name('dashboard.index');

DashboardController.php

public function getAll()
{
    $articles = Article::get();
    $users = User::get();
    $matches = Match::get();
}
Activity icon

Replied to Problem With Validation On Login Form In Laravel

@snapey

Done that. But same results. What else should I do?

Activity icon

Replied to Problem With Validation On Login Form In Laravel

@snapey

It returns error messages.

Activity icon

Replied to Problem With Validation On Login Form In Laravel

@martinbean

Ok, so which response do you mean? Which to remove?

Activity icon

Started a new Conversation Problem With Validation On Login Form In Laravel

I have login form that uses form request validation. I have a problem on how to display errors when credentials on login form are wrong and also that those errors display in inspect element network tab. Currently it doesn't display them at all for some reason and when I dump errors variable in blade I get empty array. Any help is appreciated. Here is my code.

AbstractFormRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class AbstractFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        $errs = [];
        foreach ($validator->errors()->messages() as $key => $err) {
            $errs[] = $err[0];
        }
        $errors = implode(' | ', $errs);

        $message = [
            'error' => [
                'status_code' => 422,
                'message' => $errors
            ]
        ];
        
        throw new HttpResponseException(response()->json($message, 422));
    }


}

LoginUserRequest.php

<?php

namespace App\Http\Requests\AuthRequests;

use App\Http\Requests\AbstractPublicFormRequest;

class LoginUserRequest extends AbstractFormRequest
{

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'password' => 'required'
        ];

        if (empty($this->request->get('email'))) {
            $rules = array_merge($rules, ['username' => 'required']);
        } else {
            $rules = array_merge($rules, ['email' => 'required|email|exists:App\User,email']);
        }

        return $rules;
    }
}

login.blade.php

<div class="login-page">
    @error('not_allowed')
    {{$message}}
    @enderror
        <div class="card mb-0">
            <div class="card-body login-card-body">
                <form method="POST" class="mb-4" action="{{ route('login') }}">
                    @csrf
                    <div class="input-group mb-3">
                        <input id="email" type="email" placeholder="Email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-user"></span>
                            </div>
                        </div>
                        @error('email')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="input-group mb-3">
                        <input id="password" type="password" placeholder="Password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-eye-slash cursor-pointer" style="display: none" ></span>
                                <span class="fas fa-eye cursor-pointer"></span>
                            </div>
                        </div>
                        @error('password')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="float-right">
                        <button type="submit" class="btn btn-primary btn-block font-weight-bold">Sign In</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>