Tanvir Ahmed
Tanvir Ahmed

Reputation: 1019

How to solve the problem of getting unusual id in laravel

Here is my routes

Route::get('add-members/{id}','MemberController@create');
Route::post('save-member/{id}','MemberController@store');

This is my code to show the create form

public function create($id)
    {
        $team=Team::find($id);
        $users = User::doesntHave('teams')->whereHas('roles', function($role) {
            $role->where('name', 'member');
        })->get();
        return view('members.create',compact('users','team'));
    }

An this is my code to store it

public function store(Request $request,$id)
    {
        $team=Team::find($id);
        dd($request->id);
        $team->users()->attach($request->id);
        return redirect('home');

} and this is my blade file

@extends('layouts.app')
@section('content')
    <form action="{{url('save-member',$team->id)}}" method="post" accept-charset="utf-8">
        @csrf
        <div class="form-group row">
            <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Select Member/s') }}</label>
            <div class="col-md-6">
                @foreach($users as $key => $user)
                    <input type="checkbox" name="id[]" value="{{$user->id}}">{{$user->email}}<br>
                @endforeach
                @error('member_id')
                <span class="invalid-feedback" role="alert"><strong><font
                            color="red">{{ $message }}</font></strong></span>
                @enderror
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
@endsection

Now when i select none of the user and just click save button it will save the the user id as 1. After i am doing dd($request->id) it will show me the output 1. But in my form there is no users left or my form is empty.So where from 1 is coming. you can see this picture for clearify. enter image description here Please help me to solve this problems

Upvotes: 0

Views: 143

Answers (1)

lagbox
lagbox

Reputation: 50491

You should be more specific with what data you are requesting from the Request:

$request->id; // could be an input named 'id' or a route parameter named 'id'

$request->input('id'); // is an input
$request->route('id'); // is a route parameter

You are running into a situation where you have a route parameter named id and potentially an input named id. Using the dynamic property of the Request, $request->id, will return the input id if it is there, if not it falls back to returning a route parameter named id.

Here is an article from the past that shows the issue with not being specific about what you are trying to get from the Request object: asklagbox - blog - watch out for request

Upvotes: 2

Related Questions