How to use Nested Form Fields in Livewire? - php

I have a component called project-form and in that again I am calling another component called search-users. The problem is that I am unable to set the $members property in ProjectForm from nested component i.e search-users.
As I can understand $members must be looking to set in SearchUsers.php but I want that must be set in ProjectForm.php so I could save in db.
project-form.blade.php
<form wire:submit.prevent="submit">
<input wire:model="name"/>
<input wire:model="category"/>
<input wire:model="target_date"/>
#livewire('search-users')
</form>
ProjectForm.php
<?php
namespace App\Http\Livewire;
use App\Models\Project;
use Livewire\Component;
class ProjectForm extends Component
{
public string $name = '';
public string $category = '';
public string $target_date = '';
public array $members = [];
protected $rules = [
'name' => 'required',
'category' => 'required',
'target_date' => 'required',
];
public function submit(){
$validated = $this->validate();
Project::create($validated);
toastr()->success('Project Created Successfully');
}
public function render()
{
return view('livewire.project-form');
}
}
search-users.blade.php
#foreach($users as $user)
<label class="list-group-item ps-0 border-0 d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center">
<img alt="{{ $user->name }}" src="{{ url('storage/'.$user->avatar) }}" width="35" class="me-3 rounded-circle mx-auto d-block">
{{ $user->name }}
</div>
<input class="form-check-input me-1" wire:model.defer="members" type="checkbox" value="{{ $user->id }}">
</label>
#endforeach

As already suggestes by #Qirel you should use Livewire events.
In your search components you could emit an event memebersFound and passing the members from your search as parameter (see Livewire Passing parameters in events) like this
$this->emit('membersFound', $membersFound);
Then, in your ProjectForm component you should listen for this event
protected $listeners = [
'membersFound' => 'addMembers'
];
public function addMembers(array $members)
{
$this->members = $members;
}

Related

post request not working in laravel livewire

hello guys I'm new to laravel and livewire please kindly assist, post request not going through , if i click on the submit nothing is happening, I'm not getting error either, I have added the livewire script in my app.blade.php and it's rendering properly
Post Create form
<div>
<div class="p-4 mx-auto mt-3 bg-gray-100 md:p-8 md:w-4/5 md:mt-0">
<h1 class="mb-3 text-xl font-semibold text-gray-600">New post</h1>
<form wire:submit.prevent="createPost" action="#" class="px-4 py-6 space-y-4">
<div class="overflow-hidden bg-white rounded-md shadow">
<div class="px-4 py-3 space-y-8 sm:p-6">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6 sm:col-span-3">
<input class="w-full" type="text"
wire:model="post.title" placeholder="Post title" />
</div>
</div>
<div class="flex flex-col">
<textarea id="body" rows="4" wire:model="post.body"
class="border-gray-300 rounded-sm form-textarea">
</textarea>
</div>
</div>
<div class="px-4 py-3 text-right bg-gray-50 sm:px-6">
<button type="submit" class="inline-flex justify-center">
post
</button>
</div>
</div>
</form>
</div>
</div>
this is my post create livewire method
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
use Illuminate\Http\Response;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'title' => 'required|min:4',
'body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = Post::create([
'user_id' => auth()->user()->id,
// 'category_id' => $this->category,
'body' => $this->body,
'title' => $this->title,
]);
$users = auth()->user();
$users->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
There are two thing here to note - you don't initialize $this->post and you don't have the proper validation. You need to check for post.title and post.body, and you also need to display the actual errors.
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function mount()
{
$this->post = new Post;
$this->post->user_id = auth()->id();
}
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'post.title' => 'required|min:4',
'post.body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = $this->post->save();
auth()
->user()
->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
To display the errors from validation, you can add the following snippet in your blade-file,
#if ($errors->any())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
Add lazy to the wire.model:
<input class="w-full" type="text" wire:model.lazy="post.title" placeholder="Post title" />
<textarea id="body" rows="4" wire:model.lazy="post.body" class="border-gray-300 rounded-sm form-textarea"></textarea>

Method Livewire\Redirector::withInput does not exist. in laravel

I am using live wire and when I try to validate the form it say
Method Livewire\Redirector::withInput does not exist.
and this is my code
Posts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
class Posts extends Component
{
public $title;
public $content;
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
public function save(){
$data = [
'title' => $this->title,
'content' => $this->content,
'user_id' => Auth()->user()->id
];
Post::create($data);
$this->cleanVars();
}
private function cleanVars(){
$this->title = null;
$this->content = null;
}
public function render()
{
return view('livewire.posts');
}
}
livewire view
<div>
<label>Title</label>
<input wire:model="title" type="text" class="form-control" />
#error('title')
<p class="text-danger">{{ $message }}</p>
#enderror
<label>Content</label>
<textarea wire:model="content" type="text" class="form-control"></textarea>
#error('content')
<p class="text-danger">{{ $message }}</p>
#enderror
<br />
<button wire:click="save" class="btn btn-primary">Save</button>
</div>
also I putted this view in home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#livewire('posts')
</div>
</div>
</div>
</div>
</div>
#endsection
Really you need to fix the header of this question, is repeating the same and you're missing something there to the community. I see in your code this and I dislike this use
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
I mean, this validation running on every hydration isn't a good approach of this. Instead, declare the rules
protected $rules = [// rules here];
//or
public function rules()
{
return [
//rules here
];
}
then you can validate the entries, for example on real-time validation using the validateOnly method inside the updated()
public function updated($propertyName)
{
$this->validateOnly($propertyName, $this->rules());
}
or just use it in the save method
public function save()
{
$this->validate(); // in the protected $rules property
// or
Post::create($this->validate());
}

ArgumentCountError Too few arguments to function App\Http\Controllers\Shop\CartController::addToCart()

So this function is supposed to add the product into a cart, but i've been getting the error
Too few arguments to function
App\Http\Controllers\Shop\CartController::addToCart(), 0 passed in
C:\xampp\htdocs\nerdS\vendor\laravel\framework\src\Illuminate\Routing\Controller.php
on line 54 and exactly 1 expected
I tried changing key words here and there on my controller, but nothing seems to do it. This is the the controller:
<?php
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
Use App\Models\Product;
Use App\Models\Order;
class CartController extends Controller {
public function placeOrder() {
if(session('id')){
if(\Cart::count()){
\App\Models\Order::store();
return redirect('shop')->with('status', 'Thank you for buying!');
}
return redirect('cart');
}
session(['place-order-process' => true]);
return redirect('login')->with('status', 'To complete your order, please log in. Not a member yet? Join the club! ');
}
public function deleteCart() {
\Cart::destroy();
return redirect('shop')->with('status', 'The cart is now empty.');
}
public function deleteItem($rowId) {
\Cart::remove($rowId);
return redirect('cart')->with('status', 'The item was deleted.');
}
public function updateCart(Request $request){
\Cart::update($request->rowId, $request->quantity);
$data = [
'cart_count' =>\Cart::count(),
'cart_total' => \Cart::total(),
'product_total' => \Cart::get($request->rowId)->total(),
];
return json_encode($data);
}
public function displayCart() {
\Cart::setGlobalTax(0);
$data['items'] = \Cart::content();
$data['total'] = \Cart::total();
return view('cart.cart', $data);
}
public function addToCartByQty (Request $request){
\App\Models\Product::addToCart($request->id, (int) $request->quantity);
return \Cart::count();
}
public function addToCart ($id){
\App\Models\Product::addToCart($id);
return \Cart::count();
}
}
My model for products:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Product extends Model {
public function category() {
return $this->belongsTo('App\Models\Category');
}
public static function deleteProduct($id){
$product = self::findOrFail($id);
Storage::disk('public')->delete($product->image);
self::destroy($id);
}
public static function editProduct($request){
$product = self::findOrFail($request->product);
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
if ($request->image){
Storage::disk('public')->delete($product->image);
$product->image = $request->image->store('images/products', 'public');
}
$product->save();
}
public static function getProductById($id){
return self::finOrFail($id);
}
public static function store($request){
$product = new self();
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
$product->image = $request->image->store('images/products', 'public');
$product->save();
}
public static function getAll(){
return self::orderBy('slug')->get();
}
public static function addToCart($id, $qty = 1){
$product = self::findOrFail($id);
\Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => $qty,
'price' => $product->price,
'weight' => 0
]);
}
public static function getProduct($cat, $pro){
$product = self::where('slug', $pro)->firstOrFail();
$product_cat = $product->category->slug;
//retun ($product_cat === $cat) ? $product_cat: false;
abort_if($product_cat !== $cat, 404);
return $product;
}
//use HasFactory;
}
The page view:
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart')}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
and my route:
Route::get('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
You need to pass the $product->id in the form action's url(). That route parameter needs to be there so that it is received in the addToCart method in controller
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart/' . $product->id)}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
And you have declared your route as get instead of post. Following restful conventions your route should be declared as a post route
Route::post('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
There is a mismatch in your route (Route::get('add-to-cart/{product_id}) and the parameter passed in your function addToCart ($id)
Had u provide product_id in route (add-to-cart/{product_id})?
Since you are using a GET route vs POST, you have to change your form method from POST to GET and also pass the id in the action url -
<form id="add-to-cart" method="get" action="{{url('add-to-cart/' . $product->id)}}">
Change your definition of addToCart method in CartController as following.
public function addToCart (Request $request, $id)
{
\App\Models\Product::addToCart($id);
return \Cart::count();
}

Laravel 7 Delete array or single image from db and disk - Deletes post but not associated images from db nor disk

In Laravel 7, I am have a task management app. I can upload tasks (posts if it were a blog) and images. I have a multiple image upload working as expected. When it comes time to delete a task, the task deletes just fine but the images are left in the database and in the disk which is public into a folder called task-images. Being new to Laravel, I am struggling on how to go about this. I tried to change the settings in the filesystem.php (which I will post with the commented out code) but that didn't change the location as I had expected. In the end, I want to be able to delete the multiple images when I delete a post and also click delete on an individual image and delete that from both db and disk. I am using resource controller for all my task routes. I have no idea how to go about this and the tutorials that I have found don't really address my specific issue. Any help would be greatly appreciated. Thank you in advance.
Here is my task controller at TaskController.php
<?php
namespace App\Http\Controllers;
use App\Task;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class TasksController extends Controller
{
public function index()
{
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return view('/tasks')->with('tasks', $tasks);
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', ['task' => $task]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
$task->update();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
// $image = '/task-images/' . $task->image;
Storage::delete($task->image);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
filesystem.php (just the disks section)
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
...
in my individual show template, show.blade.php complete in case there is a code conflict.
#extends('layouts.master')
#section('content')
<div class="container">
Go Back
<div class="card p-3">
<div class="row">
<div class="col-md-4 col-sm-12">
<h3>Task</h3>
<p>{{ $task->task_name }}</p>
<h3>Assigned On:</h3>
<p>{{ $task->created_at->format('m/d/Y') }}</p>
<h3>Assigned To:</h3>
<p>{{ $task->task_assigned_to }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Task Description</h3>
<p>{{ $task->task_description }}</p>
<h3>Priority</h3>
<p>{{ $task->task_priority }}</p>
<h3>Status</h3>
<p>{{ $task->task_status }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Test Environment Date:</h3>
<p>{{ $task->task_to_be_completed_date }}</p>
<h3>Notes</h3>
<p>{{ $task->task_notes }}</p>
<h3>Action</h3>
<div style="display: inline;">
<a href="/tasks/{{$task->id}}/edit" class="btn btn-sm btn-primary mr-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
<form style="display: inline;" action="/tasks/{{ $task->id }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
<div class="col-md-12">
<h5>Images</h5>
<hr />
<div class="row">
#if($task->image->count()>0)
#for($i=0; $i < count($images = $task->image()->get()); $i++)
<div class="col-lg-4 col-md-6 col-sm-12">
<img class="w-50 mb-2" src="/task-images/{{ $images[$i]['name'] }}" alt="">
<form style="display: inline;" action="/tasks/{{ $task->name }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
#endfor
#else
<p>No images found</p>
#endif
</div>
<br />
</div>
</div>
</div>
</div>
<!--Modal Start-->
<div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-content">
<div class="modal-body">
<img class="w-100" src="" alt="" />
</div>
</div>
</div>
</div>
<!--Modal End-->
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var $lightbox = $('#lightbox');
$('[data-target="#lightbox"]').on('click', function(event) {
var $img = $(this).find('img'),
src = $img.attr('src'),
alt = $img.attr('alt'),
css = {
'maxWidth': $(window).width() - 100,
'maxHeight': $(window).height() - 100
};
$lightbox.find('.close').addClass('hidden');
$lightbox.find('img').attr('src', src);
$lightbox.find('img').attr('alt', alt);
$lightbox.find('img').css(css);
});
$lightbox.on('shown.bs.modal', function (e) {
var $img = $lightbox.find('img');
$lightbox.find('.modal-dialog').css({'width': $img.width()});
$lightbox.find('.close').removeClass('hidden');
});
});
</script>
#endsection
In my Task model, Task.php, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
class Task extends Model
{
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function image()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
}
and finally my Image Model Image.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Task;
class Image extends Model
{
protected $fillable = [
'task_id',
'name',
];
protected $uploads = '/task-images/';
public function getFileAttribute($image)
{
return $this->uploads . $image;
}
public function task()
{
// return $this->belongsTo('App\Task', 'task_id');
return $this->belongsTo(Task::class);
}
}
If I am missing something, please let me know so I can edit my question. Again, thank you in advance for helping me with this issue. I have been scratching my head all week on this one. Cheers.
Edit
After implementing boot functions in my model as suggested below, I received an error that an invalid argument was used for foreach. I ran a dd($task); and the following image shows the result.
Final Edit
The answer below worked for my situation. I did have to edit some things to finalize the resolution:
in Task.php I changed the foreach to the following.
foreach($task->image ?: [] as $image)
I had declared image and not image in my model and that was causing a problem. Adding the ternary operator also helped the code not throw any errors.
In my TasksController.php I changed both the update and create functions with the same ternary operator as follows:
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
I hope this helps anyone else having the same issue. Thanks to #GrumpyCrouton and #lagbox for their help in resolving this as well as #user3563950
Without them, I would still by stratching my head for another couple of weeks.
on your App\Image class, implement to boot function with the following;
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($image) {
Storage::delete(Storage::path($image->name));
});
}
Also implement the boot method in App\Task class
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($task) {
foreach($task->images as $image) {
$image->delete();
}
});
}
Now on your TaskController implement the destroy method as follows;
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
As a bonus, learn Laravel model binding to ease the pain of finding an instance using findOrFail()

Receiving Argument #2 should be an array in laravel

I banged my head against the walls for 2 days now and I can't seem to shake this error.
I am receiving this error:
ErrorException (E_WARNING)
array_map(): Argument #2 should be an array
What I am trying to do: Each user can have a list of urls in the database. The same url can be in two or more user account, so it is a many to many relationship.
My UrlsController looks like this:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Urls;
use Illuminate\Http\Request;
use Auth;
class UrlsController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function index(User $user)
{
return view('editurl', compact('user'));
}
public function store(User $user) {
$user_id = Auth::user()->id;
$data = request()->validate([
'user_id' => $user_id,
'url' => 'required',
]);
auth()->user()->userurls()->create([
'user_id' => $data['user_id'],
'url' => $data['url'],
]);
return redirect("/url/" . auth()->user()->id);
}
}
My Urls model looks like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Urls extends Model
{
//protected $quarded = [];
protected $fillable = ['user_id','url'];
protected $table = 'userUrls';
public function user()
{
return $this->belongsToMany(User::class);
}
}
My blade file looks like this:
#extends('layouts.pagprincipala')
#section('content')
<section id="home" class="home pt-5 pb-5">
<div class="container mb-5">
<div class="row">
<div class="col-md-8">
<h1 class="h4">Adaugare url-uri</h1>
<hr class="bg-dark w-25 ml-0">
<p>
<form action="/url/{{$user->id}}" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="form-group row">
<label for="url" class="col-md-12 col-form-label">Adaugare URL (doar emag si pcgarage)</label>
<input id="url"
type="text"
class="form-control{{$errors->has('url') ? 'is-invalid' : ''}}"
name="url"
autocomplete="url" autofocus>
#if($errors->has('url'))
<span class="invalid-feedback" role="alert">
<strong class="text-danger">Campul url este obligatoriu.</strong>
</span>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Adaugare URL</button>
</div>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</section>
#endsection
Also, my routes look like this:
Route::get('/url/{user}', 'UrlsController#index')->name('editurl');
Route::post('/url/{user}', 'UrlsController#store')->name('updateurl');
Can you give me a suggestion on how to move forward from this ?!
The problem is in your validator:
$data = request()->validate([
'user_id' => $user_id,
'url' => 'required',
]);
You try to validate the user_id with a rule that is the user id. What you probably want to achieve is 'user_id' => 'integer', or you can drop this rule all together as you know who the user is because of Auth()->user(). This should do:
$data = request()->validate([
'url' => 'required|url', //checks if it is an URL
]);
What we don't know is how your User model is constructed. With a many to many you need a pivot table urls_users or user_urls_users with url_id and user_id which means you don't need a user_id in the userUrls table, just id and url. But that's another issue. If you want to make sure any user has any url only once, you can use the ->sync() methode.

Categories