1

I want to pass value of select list from view to my controller.The value is course_id. When I put dd(request->all()) in my controller, course_id is an string.In controller I cast it to integer and I assign to model object but always zero is inserted in course_id field of media table. this is my view:

<form action="../media" method="post" enctype="multipart/form-data">
{{csrf_field()}}
title: <input type="text" name="title">
<br> <br>
type:
<input type="radio" name="type" value="voice" checked>Voice<br>
<input type="radio" name="type" value="video">Video<br>
<br> <br>
link: <input type="file" name="link">
<br><br>
course:
<select name="$courses" >
    @foreach($courses as $course)
        <option value="{{$course->id}}">
            {{$course->title}}
        </option>
    @endforeach
</select>
<br><br>
<input type="submit">

this is store controller:

 public function store(Request $request)
{
    //dd($request->all());
    $media=new Media();
    $media->title=$request->title;
    $media->type=$request->type;
    $media->course_id=(int)($request->courses);
    $media->save();
    $format=$request->file('link')->getClientOriginalExtension();
    $size=$request->file('link')->getSize();
    $name=$request->type.'-'.$media->id.'.'.$format;
    $request->file('link')->move(public_path('medias'),$name);
    $media->link= $name;
    $media->format=$format;
    $media->size=$size;
    $media->save();
    return back();
}

And this is create controller:

 public function create()
{
    $courses=Course::all();
    return view('Admin.Media.create',compact('courses'));
}
2
  • Check your rendered HTML; I'm not sure what name="$courses" is going to render as, but at a glance I don't think it would be course_id. Also, you say "in my controller, course_id is an string.In controller I cast it to integer [...]" but you're actually casting $request->courses and not $request->course_id; gotta do some more thorough debugging on your end. Commented Oct 15, 2018 at 19:04
  • The name of course_id is courses in html view and I mentioned it in select tag. Even I receive all courses of course table in select list in my view. I only can't convert string to integer. Commented Oct 15, 2018 at 19:32

1 Answer 1

1

If you use

select name="$courses"

in your HTML, you're gonna get

"$courses" => null, // or 1, 2 etc. 

in your $request variable; which is going to be difficult to access. Use

select name="courses" <!-- Without the $ -->

And access as $request->courses in your Controller.

Note: You shouldn't have to cast to int due to the way PHP handles types, but likely doesn't hurt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.