TomasAm

TomasAm

Member Since 7 Months Ago

Experience Points
1,270
Total
Experience

3,730 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.

Level 1
1,270 XP
Oct
24
2 days ago
Activity icon

Started a new Conversation Additional Method In Resource Controller On Laravel 8

Recently I upgraded laravel to 8 and cannot find out how to add additional methods to resource controller.

The "list" controller below is not working.

Route::get('/list', [PostingController::class, 'list']);
Route::get('/', [PostingController::class, 'index']);

And my controller:

    public function list()
    {
         $categories = Category::get();
       return view('welcome', compact('categories'));
    }

It return page not found. What could be the issue? I also removed all routes and resource controllers work without mentioning them in web.php. What could be the issue?

Jul
20
3 months ago
Activity icon

Replied to Paginate Related Data Through Eloquent

yes, I made a typo, but that is not the problem. I am selecting here a category, but in the view I am looping through products related to that category. I would like to show only a few and then paginate the rest with links. If I just put ->paginate() ir returns error:

Facade\Ignition\Exceptions\ViewException
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$products (View: C:\laragon\www\project2\resources\views\products\products.blade.php)

Since I am taking a category not all products

Activity icon

Started a new Conversation Paginate Related Data Through Eloquent

I have a controller which selects a category:

       ...
        ...

        $category  = Category::where('name', $path)->firstOrFail();
        return view('products.products', compact('data', 'products', 'path', 'product', 'category'));
    }

How should I edit may controller so I could use it something like this in Blade:

@foreach ($category->products as $product)
.......
@endofreach
{{ $products->links() }}

I tried:

  $category  = Category::where('name', $path)->firstOrFail()->paginate(9);

But it seems it is not the way it works, since here I am selecting a category not products.

Jul
11
3 months ago
Activity icon

Started a new Conversation Cannot Return A Variable

Why I cannot return $path variable in the below code?

$path = $request->path();
        $data = DB::select(DB::raw('select * from categories', [1]));
         $products = DB::select(DB::raw('select * from products', [1]));
      
        return view('products.products', ['data' => $data], ['products' => $products], ['path' => $path]);

    }```

When I try to display it like {{$path}} it says undefined.
Activity icon

Started a new Conversation Raw Query Pagination

How do I paginate a raw call from database?

  public function index()
    {
        $data = DB::select(DB::raw('select * from categories', [1]));
        $products = DB::select(DB::raw('select * from products', [1]))->paginate(8);
        dd($products);
        return view('products.products', ['data' => $data], ['products' => $products]);

    }

I tried this, but it returns "Call to a member function paginate() on array"

Jun
24
4 months ago
Activity icon

Started a new Conversation Set Up Webpack Manually With Bootstrap And Vue.js, No Mix And Vue-cli

I am following these episodes for setting up webpack in laravel project:

https://laracasts.com/series/learn-vue-2-step-by-step/episodes/22 and https://laracasts.com/series/webpack-for-everyone

However, the episodes are not specific about laravel part.

What would be the basic points to set up a webpack manually with bootstrap and vue.js in a simple Laravel project, while not using mix and vue-cli? Any materials appreciated.

Jun
07
4 months ago
Activity icon

Started a new Conversation Seperating Data By Putting User_id In Each Table

I have a simple app, which does not contain too much sensative data. It is basically a tool where not related users can save and use some data.

Now I want to seperate data that they save, so only they can see and manipulate it.

I read that you can make your own multitenancy or use packages, which I found a bit complicated for my level of experience.

Would it be a sollution to add an user_id to to each record in all tables. And the use policies like this:

Route::get('/instructions/show/{instruction}', '[email protected]')->name('show_instruction');

Then policy:

 public function show_instruction(User $user, Intruction $instruction)
    {
        return $user->id === $instruction->user_id;
    }

Would it be safe enough?

May
31
4 months ago
Activity icon

Started a new Conversation Controller Not Updating After Assigning Policy Construct

In my controller I assigned policy construct:

  public function __construct() {
        $this->authorizeResource(Instruction::class, 'instruction');
    }

My update method before was:

  public function update(Request $request, $id)
    {
        $instruction = Instruction::findOrFail($id);
        $instruction->update($request->except('_token'));
        return back()->with('success', 'Record Deleted Successfully!');
    }

Now I am trying to change so it uses policy:

  public function update(Instruction $instruction)
    {
        $instruction->update();
        return back()->with('success', 'Record Deleted Successfully!');
    }

Dump:

Instruction {#370 ▼
  #table: "instructions"
  #fillable: array:2 [▼
    0 => "title"
    1 => "description"
  ]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:6 [▶]
  #original: array:6 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

However, data is not being saved. The rest methods work fine. Why is it so?

Activity icon

Started a new Conversation Redirect After Policy Authorization Fails

I am not sure when to use policies and when gates.

I have made gates which allow or deny access to some modules. These app modules are visible to all users. So when not authorized user clicks on some module, he is redirected back with an error. For example:

 public function show(User $user)
    {
        if(Gate::denies('showme-admin')) {
            return back()->with('confirm', 'Access denied!');
        }
    }

Then I read in Laravel documentation that regarding CRUD operations you should use policies. So I made a policy for one module. The thing is that while using policies I cannot redirect. Is it how it is supposed to be? Does it mean that I should make also the buttons of operations invisible? Since if my user clicks on unauthorized operation he will get 403 error.

I tried to redirect with policy with no luck like that:

    public function edit(Instruction $instruction)
    {
        if($this->authorize('view', $instruction)) {
        $instructions = Instruction::orderBy('id', 'desc')->paginate(9);
        $selectedTitle = Instruction::first()->id;   
        return view('instructions.edit', compact('instruction', 'instructions', 'selectedTitle'));      
    }
    return redirect('/instructions');
}

Should I use gates for such cases instead? Or a better practice is to use policies and avoid showing buttons with not authorized operations by policy?

May
30
4 months ago
Activity icon

Replied to Using A Policy In Controller Or Route

same error, do I need to change also in my controller ?

   public function edit($id)
    {
            $selectedTitle = Instruction::first()->id;
            $instruction = Instruction::findOrFail($id);
            $instructions = Instruction::orderBy('id','desc')->paginate(9);
            return view('instructions.edit', compact('instruction', 'instructions', 'selectedTitle'));      
    }

or blade?

  <a href="{{route('edit_instruction', $instruction->id)}}" class="btn btn-info btn-xs"><i class="fas fa-edit"></i></a>
Activity icon

Replied to Using A Policy In Controller Or Route

I will try. If I write:

Route::get('/instructions/edit/{id}', '[email protected]')->name('edit_instruction')->middleware('can:view,instruction');

It says action unauthorized 403 for a user which has the role.

Activity icon

Started a new Conversation Using A Policy In Controller Or Route

I have a policy:

 public function view(User $user, Instruction $instruction)
    {
        return $user->hasRole('view');     
    }

I can now show data if user has the role:

  @foreach($instructions as $instruction)
            <tr scope="row">
    @can ('view', $instruction)
        <td>{{$instruction->title}}</td>
        <td>{{$instruction->created_at}}</td>
        <td>{{$instruction->updated_at}}</td>
            @endcan
        @endforeach

How can I do that in controller and or route? For example, I have a controller methods like create, edit and if the user does not have the role, I want to redirect him back with message "access denied".

For example in this controller:

   public function edit($id)
    {
            $selectedTitle = Instruction::first()->id;
            $instruction = Instruction::findOrFail($id);
            $instructions = Instruction::orderBy('id','desc')->paginate(9);
            return view('instructions.edit', compact('instruction', 'instructions', 'selectedTitle'));      
    }
May
21
5 months ago
Activity icon

Replied to User Should Be Able To See Only Data He Posts

seems sollution was gates:

   public function boot()
    {
        $this->registerPolicies();
Gate::define('view-instruction', function($user, $instruction) {
$instructionBelongsToUser = $user->id === $instruction->user->id;
return $instructionBelongsToUser;
        });
May
18
5 months ago
Activity icon

Started a new Conversation User Should Be Able To See Only Data He Posts

I made a simple Laravel application. And would like to have multiple users (no admins) to be able to register and see and modify only their own data.

What things should I consider for such an application?

I have for example default Laravel login system with table:

id|name|email|password|remember_token

Then let's say I have another table:

id|title|description|created_at|updated_at

My controller with function index():

 public function index()
    {
        $instructions = Instruction::orderBy('id','desc')->paginate(9);
        return view('instructions.instruct_list', compact('instructions'));
    }

Route:

Route::get('/instructions', '[email protected]');
  1. I understand I should make migrations for each table and add something like user_id.
  2. I should find out about Laravel auth and sessions (still trying to understand the documentation). I should retrieved user id like $id = Auth::id();.
  3. And how would my shown controller and route change so the user could see and modify only his own data?
May
17
5 months ago
Activity icon

Replied to How To Update OneToMany Relations

I modified it again and your suggestion worked:

 $project = Project::findOrFail($id);
            $project->update($request->except('_token'));
        
            $task_ids = $request->input('tasks.task_id');
            $descriptions = $request->input('tasks.t_description');
            foreach($task_ids as $index => $task) {
                $project->tasks()->where('id',$task)->first()->update([
                  't_description' => $descriptions[$index]
                ]);   
Activity icon

Replied to How To Update OneToMany Relations

Do you mean something like this:

   $project = Project::findOrFail($id);
            $project->update($request->except('_token'));
            $description = $request->input('tasks.t_description');
            $task_ids = $request->input('tasks.task_id');
             foreach($task_ids as $task ) {
                $project->tasks()->where('id',$task)->first()->update([
                  "t_description" => $description
                ]);                 
            } 

And how do I specify my data? And is it sure I need first()? So far It updated in all tasks same description:

    ["description 1","description 2",".....
Activity icon

Started a new Conversation How To Update OneToMany Relations

I am storing data likes this:

   
       $descriptions = $request->input('tasks.t_description');
       $project_ids = $request->input('tasks.project_id');
        foreach($description as $index => $description) {
              $emps2 = new Task;
              $emps2->t_description = $description;
              $emps2->project_id = $project_ids[$index];
              $emps2->save();

I am trying to modify this store controller to update controller. My edit front end:

<!-- edit task -->
 @foreach ($project->tasks as $task) 
 <div>
	<div class="md-form"><textarea id="form7" class="md-textarea form-control" name="tasks[t_title][]" rows="3">
    {{$task->t_description}} 
	</textarea>
		<label for="form7">Task description<br> Project id </label><input type="number" name="tasks[project_id][]" value="{{$project->id}}">
        <label for="form7">Task description<br> Project id </label><input type="number" name="tasks[task_id][]" value="{{$task->id}}">
    </div>
</div>
@endforeach 
<!-- edit task -->

Now I want to edit all tasks from one page linked with one project. Im trying with no luck:

   $project = Project::findOrFail($id);
            $project->update($request->except('_token'));
            $description = $request->input('tasks.t_description');
            $task_ids = $request->input('tasks.task_id');
             foreach($task_ids as $task ) {
                $updates = $project->tasks()->where('task_id',$task);
                $updates = t_description?
                $updates->update();                 
            } 

Request:

  "tasks" => array:3 [▼
    "t_title" => array:14 [▶]
    "project_id" => array:14 [▶]
    "task_id" => array:14 [▶]
  ]

How could I modify my store controller to update and target all tasks related to one project?

Activity icon

Replied to Is It Good To Return A Lot Of Compact Data Sets To View From One Controller?

it is quite amateur:

 public function show($id)
    {
        $project = Project::findOrFail($id);
        $today = date("Y-m-d");
        $deadline = Project::findOrFail($id)->ends_at;
        $startsat = Project::findOrFail($id)->starts_at;
        $startsat1 = strtotime($startsat);
        $today1 = strtotime($today);
        $deadline1 = strtotime($deadline);
        $totaldays = ($deadline1-$startsat1)/86400;
        $daysleft = ($deadline1-$today1)/86400;
        $data = Project::orderBy('created_at', 'desc')
                 ->take(3)
                 ->get();
      /*   $data = Underperformance::orderBy('created_at','asc')->simplePaginate(3); */
        $dataone = Project::findOrFail($id);
$countsi = Project::findOrFail($id);
$all= $countsi->tasks()->count();
$allhours = Project::findOrFail($id);
$sum = $allhours->tasks()->sum('t_hours');
$finished_t = $countsi->tasks()->where('t_status', 'finished')->sum("t_hours")*100/$sum;
$created_t = $countsi->tasks()->where('t_status', 'created')->sum("t_hours")*100/$sum;
$started_t = $countsi->tasks()->where('t_status', 'started')->sum("t_hours")*100/$sum;
$finished_q = $countsi->tasks()->where('t_status', 'finished')->count();
$created_q = $countsi->tasks()->where('t_status', 'created')->count();
$started_q = $countsi->tasks()->where('t_status', 'started')->count();
$started = $countsi->tasks()->where('t_status', 'started')->count()*100/$all;
$created = $countsi->tasks()->where('t_status', 'created')->count()*100/$all;
$finished = $countsi->tasks()->where('t_status', 'finished')->count()*100/$all;
       
return view('projects/viewProject', compact('project','data', 'dataone', 'today',
 'daysleft', 'started', 'finished', 'created', 'finished_t',
'started_t', 'created_t', 'totaldays', 'finished_q',
'started_q', 'created_q'));  
    }
May
11
5 months ago
Activity icon

Started a new Conversation Is It Good To Return A Lot Of Compact Data Sets To View From One Controller?

I was wondering if is it ok to return many data sets like this:

return view('panel', compact('data', 'dataone', 'today',
 'daysleft', 'started', 'finished', 'created', 'finished_t',
'started_t', 'created_t', 'totaldays' .........));

Does it make the app load longer or cause issues, is there a better practice?

May
10
5 months ago
Activity icon

Started a new Conversation How To Get A Sum Of Related Collumn

I have two tables. Many tasks to one project:

tasks table: |id|project_id|t_hours|t_status..
projects table: |id|title|...

I am trying to get a total hours of all tasks related to the projects table.

So far I am able only to calculate the sum of tasks in my controller with a specific status:

$countsi = Project::orderBy('created_at', 'desc')->first();
$started = $countsi->tasks()->where('t_status', 'started')->count();

It returns 7 tasks for example, but each task may contain different number of hours. How would I modify my code to get the sum of hours from all tasks related to the project?

May
05
5 months ago
Activity icon

Awarded Best Reply on Post With Ajax And Bootstrap Modal

Change to

data: {
    formData: $('#addform').serialize()
}

and in Controller method

public function store(Request $request)
{
    parse_str($request->formData, $output);
    $tasks = new Task;
    $tasks->t_title = $output['t_title'];
    $tasks->project_id = $output['project_id'];
    $tasks->save();
}
Activity icon

Replied to Post With Ajax And Bootstrap Modal

Change to

data: {
    formData: $('#addform').serialize()
}

and in Controller method

public function store(Request $request)
{
    parse_str($request->formData, $output);
    $tasks = new Task;
    $tasks->t_title = $output['t_title'];
    $tasks->project_id = $output['project_id'];
    $tasks->save();
}
May
04
5 months ago
Activity icon

Replied to Post With Ajax And Bootstrap Modal

I changed accordingly and URL goes after submit to:

http://project2.test/tasks?_token=C7H5HUPu4DCWSHsreYaA8Wm3qT5LxPQ9z1Guc5dZ&t_title=fdgfds&project_id=3

but data not saved.

If I try to enter two text values, then get alert "data saved", if I enter project_id as intiger like 1,2,3.. it says "data saved", but it does not appear in database.

May
03
5 months ago
Activity icon

Replied to Post With Ajax And Bootstrap Modal

yes, the folder exists, no typo. Maybe the error is in html?

<div class="container">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#studentaddmodal">
  Launch demo modal
</button></div> 

<!-- Modal -->
<div class="modal fade" id="studentaddmodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="addform">
      <div class="modal-body">
      
     @CSRF
  <div class="form-group">
    <label>Title</label>
    <input type="text" name="t_title" class="form-control"  placeholder="Title">
  </div>
  <div class="form-group">
    <label>Description</label>
    <input type="text" name="project_id" class="form-control"  placeholder="Description">
  </div>
  
 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>
      </div>
   
  </div>
</div>
   </form>
Activity icon

Started a new Conversation Post With Ajax And Bootstrap Modal

I am using code.jquery.com/jquery-3.5.0.js in my application, and trying to post data without reload. It posts fine without ajax, but not with ajax script. Controllers:

 public function index()
    {
      $tasks = Task::orderBy('id','desc')->paginate(9);
      return view('empmodel', compact('tasks'));
    }
  public function store(Request $request)
    {
       $tasks = new Task;
       $tasks->t_title = $request->input('t_title');
       $tasks->project_id = $request->input('project_id');
       $tasks->save();
       return view('secondp');
    }

Ajax:

<script type="text/javascript">
$(dcument).ready(function () {
  $('#addform').on('submit', function(e){
    e.preventDefault();

    $.ajax({
      type: "POST",
      url: "/addstudent",
      data: $('#addform').serialize(),
      success: function (response) {
        console.log(response)
        $('#studentaddmodal').modal('hide')
        alert("data saved");
      },
      error: function(error) {
        console.log(error)
        alert("Data not saved");
      }
    });
  });
});
    
</script>
</body>

Routes:

Route::get('/tasks', 'projects\[email protected]');
Route::post('/addstudent', 'projects\[email protected]');

CSRF token is also not missing, so what could be the error? It seems not even showing console logs. Update: typo "dcument" changed to "document".