Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

Romentigo

Romentigo

Member Since 6 Months Ago

Experience Points
730
Total
Experience

4,270 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
0
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.

Level 1
730 XP
Jun
14
5 months ago
Activity icon

Replied to Session Not Persisting After Login, Only With Remember.

Thanks a lot! I moved all my API routes to web.php and now it works fine. Session isn't destroyed anymore. Thanks to all for help

Activity icon

Replied to Session Not Persisting After Login, Only With Remember.

No, the problem wasn't in session lifetime. Problem was in destroying session every time when I tried to use API routes.

Jun
13
5 months ago
Activity icon

Replied to Session Not Persisting After Login, Only With Remember.

@bobbybouwmann or how to make, at least, "Remember me" by default? I mean make a user always remembered.

Activity icon

Replied to Session Not Persisting After Login, Only With Remember.

@bobbybouwmann Hmm, yep, it worked just fine, thanks. One more question. It can sound weird, by I'm trying to get Auth info by Api request and it says that can't get property of non an object. For Api routes I use web middleware. How can I get Auth data? Also, session is destroyed after I try to get data from Api.

Activity icon

Started a new Conversation Session Not Persisting After Login, Only With Remember.

I've found out that session is destroyed after I login, but it keeps alive if I check "Remember me". I'm using default Auth. My routes:

Route::group(['middleware' =>['web']], function ()
{
    Route::get('/', '[email protected]')->name('welcome');
    Route::get('/login', function () {
        return view('login');
    });

    Auth::routes();

    Route::group(['middleware' => ['web','auth']], function () {
        Route::get('/profile', [
            'uses' => 'Api\[email protected]',
            'as' => 'user'
        ]);
        Route::get('/instruments', [
            'uses' => 'Api\[email protected]',
            'as' => 'instruments'
        ]);
        Route::get('/logout', 'Auth\[email protected]');
    });
});
Jun
08
5 months ago
Activity icon

Replied to Get Value Through Few Relations

Thanks a lot! You're breathtaking!

Activity icon

Started a new Conversation Get Value Through Few Relations

I have Pairs table. Model Pair belongsTo Classroom model, Classroom model belongsTo Campus model.

Pairs table:

  • id
  • classroom_id
  • ...

Classrooms table:

  • id
  • number
  • campus_id
  • ...

Campuses table:

  • id
  • name

In my Pairs table I can get Classroom's number, but I need to get somehow Campus name value right into Pairs table. With this code I get everything except campus name, only it's id:

$pairs = Pair::with('group', 'subject', 'lecturer', 'day', 'pairNumber', 'pairType', 'classroom', 'week')
            ->where('group_id', '=', $id)
            ->orderBy('day_id', 'ASC')
            ->orderBy('pair_number_id', 'ASC')
            ->get();

When I request pairs, I can see in JSON response that classroom are send as object with it's own values. But I want to insert campus object inside classroom object to get Campus name value by relations. I know that I haven't pointed Campuses relation in Pair::with, but if I do that, an exception will be thrown because of unknown relation. That what I get now in response, only campus_id:

[{id: 1, classroom_id: 14, subject_id: 3, lecturer_id: 3, group_id: 14, day_id: 1, week_id: 2,…}]
0: {id: 1, classroom_id: 14, subject_id: 3, lecturer_id: 3, group_id: 14, day_id: 1, week_id: 2,…}
classroom: {id: 14, number: 201, campus_id: 2, classroom_type_id: 1, department_id: 3,…}
campus_id: 2
classroom_type_id: 1
created_at: "2020-06-08T10:05:02.000000Z"
department_id: 3
id: 14
number: 201
updated_at: "2020-06-08T10:05:02.000000Z"
classroom_id: 14
created_at: "2020-06-08T11:10:54.000000Z"
...
Jun
07
5 months ago
Activity icon

Started a new Conversation Check If Data Exists By 2 Relationships

I have 3 models: Department, Lecturer and Subject. Department hasMany lecturers and subjects. Lecturer and subject belongsTo department. I need to get only those departments, that have at least 1 lecturer AND 1 subject. My example is next:

public function withLecturers($id)
    {
        $departments = Department::has('lecturers')->with('institute', 'lecturers')->where('institute_id', '=', $id)
            ->orderBy('name', 'ASC')->get();

        if ($departments->isEmpty())
        {
            return response()->json(['message' => 'На цьому ННІ немає жодної кафедри.'])->setStatusCode(500);
        }
        else
        {
            return response()->json($departments)->setStatusCode(200);
        }
    }

How can I use Department::has for both relations?

Jun
04
5 months ago
Activity icon

Replied to Doesn't Autologin After Registration

That's how it looks now:

Register

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{

    use RegistersUsers;


    protected $redirectTo = '/profile';


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

    protected function registered(Request $request, $user)
    {
        Auth::login($user);
    }


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

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

Login

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

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

    public function authenticated(Request $request)
    {
        return redirect('/profile');
    }

    protected function loggedOut(Request $request)
    {
        return redirect('/');
    }
}
Activity icon

Replied to Doesn't Autologin After Registration

The same problem. Seems like a user logs in, but the server drops him from Auth.

Activity icon

Started a new Conversation Doesn't Autologin After Registration

I'm using default Laravel Auth with some changes. I noticed that it doesn't log a user in after a registration. It works weird. In my app.blade it looks like this:

<body>
<nav class="navbar navbar-expand-lg navbar-light bg-white">
    <a class="navbar-brand" href="{{url('/')}}">
        <img src="{{asset('images/lis6.png')}}" width="30" alt="Logo">
        <span>ScheduleFox</span>
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link {{request()->is('instruments') ? 'active' : ''}}" href="{{url('/instruments')}}">Інструменти</a>
            </li>
        </ul>
        <div class="form-inline nav-pills my-2 my-lg-0">
            @auth
                <ul class="navbar-nav">
                    <li class="nav-item mr-3 {{request()->is('profile') ? 'active' : ''}}">
                        <a class="nav-link font-weight-bold" href="{{url('/profile')}}">{{\Illuminate\Support\Facades\Auth::user()->name}}</a>
                    </li>
                </ul>
                <a class="nav-link" href="{{url('/logout')}}">Вихід</a>
            @endauth
            @guest
                <a class="nav-link" href="{{url('/login')}}">Вхід</a>
            @endguest
        </div>
    </div>
</nav>
    @yield('content')

My navbar shows Login for guests and other elements for logged in users. The problem is next: after register my navbar changes like I'm logged in, but it's not. Nothing works, nothing is shown except navbar. When I refresh my app, it redirects me to welcome.blade and shows me a navbar as for guest. What I'm doing wrong? My Register and Login controllers:

Register

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

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

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'role_id' => ['required'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'role_id' => $data['role_id'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

Login

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{


    use AuthenticatesUsers;

    public function authenticated(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials))
        {
            return redirect('/profile');
        }
    }

    public function logout(Request $request) {
        Auth::logout();
        return redirect('/');
    }

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

UPD: It works fine when I log in manually. It just trying to log me in automatically after register and it fails.

Jun
01
5 months ago
Activity icon

Started a new Conversation Unique Fields With Conditions

I have the following migration:

PAIRS

public function up()
    {
        Schema::create('pairs', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('classroom_id');
            $table->foreign('classroom_id')
                ->references('id')
                ->on('classrooms')
                ->onDelete('cascade');
            $table->bigInteger('subject_id');
            $table->foreign('subject_id')
                ->references('id')
                ->on('subjects')
                ->onDelete('cascade');
            $table->bigInteger('lecturer_id');
            $table->foreign('lecturer_id')
                ->references('id')
                ->on('lecturers')
                ->onDelete('cascade');
            $table->bigInteger('group_id');
            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
            $table->bigInteger('day_id');
            $table->foreign('day_id')
                ->references('id')
                ->on('days')
                ->onDelete('cascade');
            $table->bigInteger('week_id');
            $table->foreign('week_id')
                ->references('id')
                ->on('weeks')
                ->onDelete('cascade');
            $table->bigInteger('pair_number_id');
            $table->foreign('pair_number_id')
                ->references('id')
                ->on('pair_numbers')
                ->onDelete('cascade');
            $table->bigInteger('pair_type_id');
            $table->foreign('pair_type_id')
                ->references('id')
                ->on('pair_types')
                ->onDelete('cascade');
            $table->unique(['week_id', 'day_id', 'classroom_id', 'pair_number_id']);
            $table->unique(['group_id', 'day_id', 'pair_number_id', 'week_id']);
            $table->unique(['lecturer_id', 'day_id', 'pair_number_id', 'week_id']);
            $table->timestamps();
        });
    }

Can I use conditions in unique arrays? For example, I have 3 types of a week: every, odd and even. If the classroom is occupied at that time on even weeks, it also can be occupied on odd weeks, even at the same time. But it cannot be occupied on every week. For example:

Week: even - Request: odd - Response: true

Week: every - Request: odd or even - Response: false

Week: even - Request: every - Response: false

So, if it's occupied every week, it cannot be occupied on odd or even week. If it's occupied on even week, it can be occupied also on odd week and vice versa. How can I do this via Laravel migrations? Or should I make it manually in my database?

Activity icon

Replied to Regex: Check A String

Thanks all for your replies! It helped a lot, both

May
31
5 months ago
Activity icon

Started a new Conversation Regex: Check A String

I have the next method:

isLetter(e) {
                let char = String.fromCharCode(e.keyCode);
                if(/^[А-я\' ІіЇїЄєҐґ]+$/.test(char)){
                    return true;
                }
                else e.preventDefault();
            },

This method doesn't allow to type any characters, except given above. It works on event @keypress. But I've noticed one problem – a user can just paste anything he wants in an input field. How can I validate the whole input field, for example, on @blur event?

May
30
5 months ago
Activity icon

Replied to How To Delete Images From Public Folder?

Yep, I've changed path several times. It was like you wrote above. Seems like Core PHP methods doesn't work properly or I use them not correctly – images disappear not instantly. Yours storage method works much better, thank you!

Activity icon

Replied to How To Delete Images From Public Folder?

Well, problem has solved itself somehow. Even when I was trying to recompile project a few times, it didn't work. When I just continued doing other tasks, they finally disappeared and were replaced by new images.

Activity icon

Started a new Conversation How To Delete Images From Public Folder?

I'm using Laravel + Vue.js with Laravel Mix. One day I added to public folder some images. I've just wanted to replace them with new ones, but there are still old images instead of new. If I add images by other names, they appear, but I can't replace old ones. I've tried code like this below:

public function removeImage()
    {
        if(file_exists(public_path('./images/students.png'))){
            unlink(public_path('./images/students.png'));
        }else{
            dd('File does not exists.');
        }
    }

I have the next path: public/images/some images. I've run this function with different images and seems like succesfully, but they are still on my server. How can I remove them?

May
29
5 months ago
Activity icon

Replied to Select All Records With At Least 1 Related Record

Thanks! Seems like I missed it in documentation somehow.

Activity icon

Started a new Conversation Select All Records With At Least 1 Related Record

Hello! I've got a question, it can be simple though. I have 2 models: Speciality and Group. Their defenitions are below:

Speciality

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Speciality extends Model
{
    protected $fillable = ['name', 'institute_id'];

    public function institute()
    {
        return $this->belongsTo('App\Models\Institute');
    }

    public function groups()
    {
        return $this->hasMany('App\Models\Group');
    }
}

Group

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $fillable = [
        'speciality_id', 'course_num', 'group_num'
    ];

    public function speciality()
    {
        return $this->belongsTo('App\Models\Speciality');
    }

    public function students()
    {
        return $this->hasMany('App\Models\Student');
    }
}

I need to get all specialities that have at least one group. That's the part of my controller that returns all specialities by institute id, but it doesn't matter now, it works fine.

Controller

public function filterByInstitute($id)
   {
       $specialities = Speciality::with('institute', 'groups')->where('institute_id', '=', $id)
           ->orderBy('name', 'ASC')->get();

       if ($specialities->isEmpty())
       {
           return response()->json(['message' => 'У системі немає жодної спеціальності.'])->setStatusCode(500);
       }
       else
       {
           return response()->json($specialities)->setStatusCode(200);
       }
   }
May
25
6 months ago
Activity icon

Started a new Conversation Validator Fails On PUT Request

I have the next method in my controller:

public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'last_name' => ['required', 'string', 'min:2', 'max:20'],
            'first_name' => ['required', 'string', 'min:2', 'max:20'],
            'middle_name' => ['required', 'string', 'min:2', 'max:20'],
            'email' => ['email', 'max:255', 'unique:users', 'unique:students', 'unique:lecturers', 'nullable'],
            'phone' => ['required', 'string', 'size:18', 'unique:lecturers', 'unique:students'],
            'degree_id' => ['required', 'integer'],
            'department_id' => ['required', 'integer']
        ], $this->messages());

        if ($validator->fails())
        {
            return response()->json($validator->messages())->setStatusCode(422);
        }

        $compare = Lecturer::where('last_name', '=', $request->last_name)
            ->where('first_name', '=', $request->first_name)
            ->where('middle_name', '=', $request->middle_name)
            ->get();

        if (!$compare->isEmpty())
        {
            return response()->json(['message' => 'Такий викладач вже існує!'])->setStatusCode(500);
        }
        else {
            Lecturer::findOrFail($id)->update($request->all());

            return response()->json(['message' => 'Викладач був оновлений!'])->setStatusCode(200);
        }
    }

So, validator checks if everything is ok, then I'm looking for existing last name, first name and middle name. If it's empty, it's allowed to update the record.

But I have a problem with validator. When I send a PUT request, validator fails. For example, I just editing first name, other fields stay the same, but on PUT request it says, that such email and phone number already exist, but they belong to person I edit at the moment, no other people have such values. How can I solve it?

Activity icon

Started a new Conversation Loading Spinner In Blade

I have layout "app.blade.php" and, for example, view "user.blade.php" with Vue components inside. I've got it how to display Vue component loading, but don't know how to do the same with Laravel views.

Yes, I know that it not works as Vue and I always get a rendered view from server. I suppose that I should insert in "app.blade" a view, for example "loading.blade", and when my view "user.blade" with parent Vue component are ready, switch views. Or it's possible to do other way?

When I use loading spinner in Vue parent component, my "user.blade" looks empty and only after a few seconds shows spinner after Vue loaded. But I need to show spinner before Vue is loaded.

My "user.blade":

@extends('layouts.app')

@section('pageTitle', 'Особистий кабінет')

@section('content')
    <div id="app">
        <manage></manage>
    </div>
    <script src="{{ asset('/js/app.js') }}"></script>
@endsection

RenderController:

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RenderController extends Controller
{
    public function welcome()
    {
        return view('welcome');
    }

    public function user()
    {
        return view('user');
    }
}