This question already has answers here:
How to make a delete request with Laravel
(2 answers)
Closed 2 years ago.
The accept button has the route route('members.update', $member->id)
The deny button has the route route('members.destroy', $member->id)
These are the cards:
#foreach ($members as $member)
<div class="my-1 px-1 w-full md:w-1/2 lg:my-4 lg:px-4 lg:w-1/3">
<article class="bg-white overflow-hidden rounded-lg shadow-lg">
<div class="flex items-center justify-between leading-tight p-2 md:p-4 w-max">
<div class="w-1/2">
<small class="text-gray-600">Full name:</small>
<h1 class="text-lg pr-2"> {{ $member->firstname }} {{ $member->lastname }} </h1>
</div>
<div class="w-1/2">
<small class="text-gray-600">Birthdate:</small>
<h1 class="text-lg">{{ date('d-m-Y', strtotime($member->birthdate)) }}</h1>
</div>
</div>
<div class="flex items-center justify-between leading-tight p-2 md:p-4">
<div class="w-1/2">
<small class="text-gray-600">Student id:</small>
<h1 class="text-lg pr-2">{{ $member->studentid }}</h1>
</div>
<div class="w-1/2">
<small class="text-gray-600">Discord:</small>
<h1 class="text-lg">{{ $member->discordname }}{{ $member->discordtag }}</h1>
</div>
</div>
<footer class="flex items-center leading-tight p-2 md:p-4 justify-start">
<form method="PATCH" action="{{ route('members.update', $member->id) }}">
#method('PATCH')
<button class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded mr-2">Accept</button>
#csrf
</form>
<form method="DELETE" action="{{ route('members.destroy', $member->id) }}">
#method('DELETE')
<button class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Deny</button>
#csrf
</form>
</footer>
</article>
</div>
#endforeach
And this is my controller:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Member;
use Illuminate\Http\Request;
class MemberController extends Controller {
public function index() {
$members = Member::where(['status' => false])->get();
return view('dashboard')->with(['members' => $members]);
}
public function show($id) {
$members = Member::where(['id' => $id])->get();
return view('dashboard')->with(['members' => $members]);
}
public function store(Request $request) {
$validatedData = $request->validate([
'firstname' => 'required|max:255|alpha|min:2',
'lastname' => 'required|max:255|alpha|min:2',
'studentid' => 'required|integer|alpha_num',
'birthdate' => 'required|date',
'discordname' => 'required|max:255',
'discordtag' => 'required|max:255|size:5'
]);
$member = new Member;
$member->firstname = $request->firstname;
$member->lastname = $request->lastname;
$member->studentid = $request->studentid;
$member->birthdate = $request->birthdate;
$member->discordname = $request->discordname;
$member->discordtag = $request->discordtag;
$member->status = false;
$member->save();
return \redirect()->route('index');
}
public function update($id) {
die;
$member = Member::find($id);
$member->status = 1;
$member->save();
return \redirect()->route('dashboard');
}
/**
* TODO - SEND EMAIL ON DELETE
*
* #return void
*/
public function destroy($id) {
DB::delete('delete members where id = ?', [$id]);
}
public function accepted($id) {
update($id);
}
}
My routes:
When i click the accept or deny button it sends me to this link: http://hit.localhost.nl/members/3?_method=PATCH&_token=0g5odDLEKCicceDOf4EuPMGIB1X95cwWHGMxMqcR
And runs the show() function instead of the update or destroy functions. What am i doing wrong here?
method="PATCH" and method="DELETE" don't exist, just get, post and dialog. Change both of those to method="post".
Related
I'm building a scrape website for my laravel project.
On my admin-page I want to be able to store multiple sorts of data like 'urls' and on another form 'categories'. So those are multiple forms on one page (not sure if that is possible..).
I wrote my function so that when my data is stored, it will refresh the page. So that worked but when I went checking in my database to verify, nothing was there and I've been setting up create functions in laravel but this one is so difficult to know where it goes wrong.
This is my code:
My admin page:
<body class="relative min-h-screen">
#include('partials.header')
<main class="">
<div class="text-center m-auto text-2xl p-4 w-fit border-b">
<h2>Welkom <strong>{{ auth()->user()->name }}</strong></h2>
</div>
<div class="gap-10 m-auto xl:w-3/5">
<div class="mt-8 min-h-screen">
<h3 class="bg-gray-100 p-4"><strong>Scrapes</strong></h3>
<div class="">
<div class="p-4 m-auto">
<form action="{{ route('admin', Auth()->user()) }}">
#csrf
<div class="flex wrap flex-row items-center justify-left my-4">
<label for="shop" class="w-2/12">Webshop:</label>
<select name="shop" id="shop" class="w-4/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100">
</select>
</div>
<div class="flex wrap flex-row items-center justify-left">
<label for="url" class="w-2/12">
Voeg een url toe:
</label>
<input type="url" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="url" id="url" placeholder="bvb.: http://dreambaby.com/speelgoed">
<button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" type="submit">Voeg link toe</button>
</div>
</form>
<form action="{{ route('admin', Auth()->user()) }}" method="POST">
#csrf
#method('PUT')
<div class="flex wrap flex-row items-center justify-left">
<label for="url" class="w-2/12">
Voeg een categorie toe:
</label>
<input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="title" id="cat" placeholder="bvb.: Eten en Drinken">
<button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" type="submit">toevoegen</button>
</div>
</form>
</div>
<div class="mt-8 p-4">
<p>Overzicht links:</p>
<ul>
</ul>
</div>
</div>
</div>
</div>
</main>
#include('partials.footer')
</body>
My Controller:
class AdminController extends Controller
{
public function showAdmin($id)
{
return view('admin');
}
public function storeCat(Request $request)
{
$cat = Category::create([
'title' => $request->input('title')
]);
echo('Tis gelukt');
return view('admin');
}
public function updateCat(Request $request, $id)
{
$cat = Category::where('id', $id)
->update([
'title' => $request->input('title')
]);
return back();
}
public function destroyCat(Request $request, $id)
{
$cat = Category::find($id)->first();
$cat->delete();
return back();
}
}
My Model:
class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fillable = [
'title'
];
protected $guarded = [
'id',
'created_at',
'updated_at'
];
}
My migration:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
My Routes:
Route::get('/admin/{id}', [AdminController::class, 'showAdmin'])
->name('admin');
Route::post('/admin/{id}', [AdminController::class, 'storeCat']);
Route::put('/admin/{id}', [AdminController::class, 'updateCat']);
Route::delete('/admin/{id}', [AdminController::class, 'destroyCat']);
I found why it was not working. I just had to remove method('PUT')
But I have no clue what to do when I actually want to edit my categories..
Good night all. I have a problem when I want to display many to many relationship data, namely postal data based on tags with livewire. Previously I tried in laravel can appear.
Now I want to display post data by tag with livewire but still can't.
the following is the code that I have made.
web.php
Route::get('tag/{tag:slug}',[FrontController::class, 'tag'])->name('tag');
FrontController.php
public function tag(Tag $tag)
{
$categories = Category::all();
$general = General::find(1);
$locale = App::currentLocale();
$search = request("search");
$posts = $tag->posts()->where([
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate(12);
if ($this->search !== null) {
$posts = $tag->posts()->where([
['title','like', '%' . $search . '%'],
['lang',$locale],
['status','PUBLISH'],
])->latest()->paginate(12);
}
// dd($posts);
$tags = Tag::all();
$top = Post::where('status','PUBLISH')->orderBy('views','desc')->limit(5)->get();
return view ('front.tag',compact('categories','general','locale','posts','tags','top'));
}
tag.blade.php
#extends('layouts.front')
#section('content')
<main id="main">
<section class="post-category">
<div class="container-fluid">
<div class="row mt-3">
<div class="col-lg-3 col-md-12 col-sm-12 d-none d-lg-block">
<div class="sticky-top" style="top: 90px;">
<div class="card mb-3 rounded-3">
<div class="card-body">
<a href="#" target="_blank" rel="noreferrer">
<img src="{{ asset('front/img/ads.png') }}" alt="..." height="300" width="279" class="card-img-top" />
</a>
</div>
</div>
<div class="d-flex flex-column mb-3 bg-light shadow bg-body rounded">
<div class="card-header bg-primary bg-gradient text-white fw-bold fs-5">
{{ __('sentence.category') }}
</div>
<ul class="list-group list-group-flush">
#foreach ($categories as $category)
<li class="list-group-item d-flex justify-content-between align-items-center">
{{ $category->name }}
</li>
#endforeach
</ul>
</div>
<div class="d-flex flex-column bg-light bg-body shadow-lg rounded-3">
<div class="card-header bg-primary bg-gradient text-white fw-bold fs-5">
Tags
</div>
<div class="p-3 overflow-auto" style="max-height: 42vh">
<div class="nav tag-cloud">
#foreach ($tags as $tag)
{{ $tag->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
<livewire:tag-index>
<div class="col-lg-3 col-md-12 col-sm-12">
<div class="sticky-top" style="top: 90px;">
<div class="card rounded-3 shadow-lg mb-3">
<div class="card-body">
<img src="{{ asset('front/img/ads1.png') }}" height="117" width="279" class="card-img-top" alt="...">
</div>
</div>
<div class="bg-light shadow bg-body rounded-3 mb-3">
<div class="card-header bg-primary bg-gradient text-white fw-bold fs-5">
{{ __('sentence.top_article') }}
</div>
<ul class="list-group list-group-flush mb-2">
#foreach ($top as $top)
<li class="list-group-item">
{{ $top->title }}
<div class="d-flex justify-content-between mt-3">
<small class="text-muted">{{ Carbon\Carbon::parse($top->created_at)->format("d F, Y") }}</small>
<small class="text-muted">{{ $top->views }} views </small>
</div>
</li>
#endforeach
</ul>
</div>
<div class="d-flex flex-column mb-3 bg-light shadow bg-body rounded d-lg-none d-xl-none">
<div class="card-header bg-primary bg-gradient text-white fw-bold fs-5">
{{ __('sentence.category') }}
</div>
<ul class="list-group list-group-flush">
#foreach ($categories as $category)
<li class="list-group-item d-flex justify-content-between align-items-center">
{{ $category->name }}
</li>
#endforeach
</ul>
</div>
<div class="d-flex flex-column bg-light bg-body shadow-lg rounded-3 d-lg-none d-xl-none">
<div class="card-header bg-primary bg-gradient text-white fw-bold fs-5">
{{ __('sentence.tag') }}
</div>
<div class="p-3 overflow-auto" style="max-height: 42vh">
<div class="nav tag-cloud">
#foreach ($tags as $tag)
{{ $tag->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
#endsection
#push('scripts')
#livewireScripts
<script type="text/javascript">
window.onscroll = function (ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
window.livewire.emit('tag-index');
}
};
</script>
<script>
document.getElementById('load-more').onclick = function() {
window.livewire.emit('tag-index');
};
</script>
#endpush
livewire\TagIndex.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\{Tag, Post};
use Illuminate\Support\Facades\App;
class TagIndex extends Component
{
public $limitPerPage = 10;
public $search;
protected $listeners = [
'tag-index' => 'TagIndex'
];
protected $updatesQueryString = [
['search' => ['except' => '']],
];
public function TagIndex()
{
$this->limitPerPage = $this->limitPerPage + 6;
}
public function render(Tag $tag)
{
$locale = App::currentLocale();
$posts = $tag->posts()->where([
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate($this->limitPerPage);
if ($this->search !== null) {
$posts = $tag->posts()->where([
['title','like', '%' . $this->search . '%'],
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate($this->limitPerPage);
}
$this->emit('postStore');
return view('livewire.tag-index', ['posts' => $posts]);
}
}
livewire\tag-index.blade.php
<div class="col-lg-6 col-md-12 col-sm-12">
<div id="section-title" class="section-title p-1 pt-3">
<h2 class="text-center fw-bold">{{ trans('sentence.recent_posts')}}</h2>
</div>
<div class="form-group has-search mb-3">
<span class="bi bi-search form-control-feedback"></span>
<input type="text" wire:model="search" class="form-control" placeholder="{{ __('sentence.search_form') }}">
</div>
#foreach ($posts as $data)
<div class="card bg-light shadow bg-body rounded-3 mb-2">
<div class="card-header bg-primary text-white d-flex justify-content-between">
<small>by {{$data->admin->name}}</small>
<small>{{ Carbon\Carbon::parse($data->created_at)->format("d F, Y") }}</small>
</div>
<div class="card-body">
<h2 class="card-title">
{{ $data->title }}
</h2>
<div class="card-footer bg-body d-flex justify-content-between align-items-center pb-0 px-0">
<div class="d-flex my-1">
#foreach ($data->tags as $tag)
{{ $tag->name }}
#endforeach
</div>
</div>
</div>
</div>
#endforeach
#if ($posts->count() == 0)
<div class="alert alert-danger" role="alert">
Data not found!
</div>
#endif
#if($posts->count() >= 10)
<div class="text-center d-md-none d-lg-none d-xl-none">
<button id="load-more" class="btn btn-primary my-3">
Load More
</button>
</div>
#endif
</div>
what is the correct way or code to display many to many relationship data with livewire? in this case, I want to display post data by tag. thank you
There is a lot of additional stuff going on in your question so I have put together a simplified example for you. You will need to do the remainder of the work to get it into your project.
I don't know how you're displaying your tag labels or anything, so I have gone with checkboxes as it seems the most sensible. These could be styled to be hidden so they more closely resemble the tag labels on SO but again, I will leave the bike shedding to you.
I created a Livewire component called Tags with an associated blade view.
tags.blade.php
<div>
{{-- loop over each of the tags --}}
#foreach ($this->tags as $tag)
{{-- wire:key is important here as Livewire requires it for effective DOM diffing! --}}
<div wire:key="tag-{{ $tag->id }}" class="block px-4 py-2">
{{--
this is where we bind the checkboxes
to a property on the Livewire component
--}}
<input wire:model="selectedTags" type="checkbox" id="tag-{{ $tag->id }}" name="{{ $tag->title }}" value="{{ $tag->id }}">
<label for="{{ $tag->title }}">{{ $tag->title }}</label>
</div>
#endforeach
{{-- loop over each of the posts --}}
#foreach ($this->posts as $post)
{{-- again, don't overlook wire:key! --}}
<div wire:key="post-{{ $post->id }}" class="block px-4 py-2">
<h4 class="text-sm">{{ $post->title }}</h4>
</div>
#endforeach
</div>
The above should be mostly self explanatory, the only bit that might not be is wire:model="selectedTags". A public property called selectedTags is defined on the Tags component (as you'll see in a moment) and what this does is allow us to manage elements in that array when one of the checkboxes is selected. So for example when someone checks the checkbox for tag with id of 12, the selectedTags array has an element added with the value of 12.
Tags.php
class Tags extends Component
{
// array of selected tags (checked checkboxes)
public $selectedTags = [];
// get just the id and title of each tag
public function getTagsProperty()
{
return Tag::select('id', 'title')->get();
}
public function getPostsProperty()
{
$tags = array_filter($this->selectedTags);
// if no tags are selected, return all posts
// you might decide to return nothing, up to you
if (!$tags) {
return Post::all();
}
// if there are some selected tags
// query the database for posts with the selectedTags
// this is an `OR` operation on tags
// if you want `AND` you'll need to change it
return Post::whereHas('tags', function ($query) use ($tags) {
$query->whereIn('tags.id', $tags);
})->get();
}
public function render()
{
return view('livewire.tags');
}
}
Again the above should be self explanatory as there is nothing out of the ordinary going on.
The getPostsProperty() and getTagsProperty() functions define computed properties which are optional, you could just use normal properties if you wish. However, if you're referencing $tags and $posts multiple times in your component views, a computed property is more performant as it doesn't make a call to the backend component each time.
SOLVED
thanks #Peppermintology for helping my two issues and now this issue is solved with below code.
FrontController.php
public function tag(Tag $tag)
{
$categories = Category::all();
$general = General::find(1);
$locale = App::currentLocale();
$tag_id = $tag->id;
$search = request("search");
$posts = $tag->posts()->where([
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate(12);
if ($this->search !== null) {
$posts = $tag->posts()->where([
['title','like', '%' . $search . '%'],
['lang',$locale],
['status','PUBLISH'],
])->latest()->paginate(12);
}
$tags = Tag::all();
$top = Post::where('status','PUBLISH')->orderBy('views','desc')->limit(5)->get();
return view ('front.tag',compact('categories','general','locale','posts','tags','tag_id','top'));
}
livewire\TagIndex.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\{Tag, Post};
use Illuminate\Support\Facades\App;
class TagIndex extends Component
{
public $limitPerPage = 10;
public $search, $tagId;
protected $listeners = [
'tag-index' => 'TagIndex'
];
protected $updatesQueryString = [
['search' => ['except' => '']],
];
public function TagIndex()
{
$this->limitPerPage = $this->limitPerPage + 6;
}
public function render()
{
$locale = App::currentLocale();
$tag_id = $this->tagId;
$tag = Tag::find($tag_id);
$posts = $tag->posts()->where([
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate($this->limitPerPage);
if ($this->search !== null) {
$posts = $tag->posts()->where([
['title','like', '%' . $this->search . '%'],
['status','PUBLISH'],
['lang',$locale],
])->latest()->paginate($this->limitPerPage);
}
$this->emit('postStore');
// dd($posts);
return view('livewire.tag-index', ['posts' => $posts, 'tag' => $tag]);
}
}
I tried many ways of populating old checked values in edit page of livewire.
Method 1 :
public $role_id, $name, $new_permissions = [];
public function mount($id)
{
/
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->toArray();
// here new_permissions is my wire:model name in view for the checkbox input
// so I tried to initialize the new_permissions array by old_permissions array
$this->new_permissions = $old_permissions;
$this->role_id = $id;
}
Method 2 :
Manually fetched the permissions in the view and checked in_array for the old_permissions to be checked:
#php
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->toArray();
#endphp
<div class="col-md-12">
<div class="form-group">
<label class="display-block text-semibold">Select Permissions</label>
#foreach($permissions as $item)
<label class="checkbox-inline">
<input type="checkbox" wire:model="new_permissions" class="" value="{{ $item->id }}" {{ in_array($item->id, $old_permissions) ? "checked" : "" }}>
{{ $item->name }} </label>
#endforeach
</div>
</div>
In the 2nd method, my code in view source was correct, the old ones had checked in input field and the new ones didnt, but in the view the checkboxes didn't appear to be checked.
Livewire use string value instead of numeric.
To fix it convert all integers in your $old_permissions array to strings like
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->->map(function ($permission_id) {
return strval($permission_id);
})->toArray();
Here is my solution
In View
<div class="bg-white dark:bg-primary-900 rounded-md shadow mt-2 py-3 px-2">
<h3 class="mb-2 text-gray-900 dark:text-gray-100 text-xl">Permissions</h3>
<div class="grid grid-cols-12 gap-4">
#foreach ($permissions as $permission)
<div class="col-span-6 sm:col-span-4 md:col-span-3 flex items-center space-x-2">
<input wire:model="selectedPermissions" type="checkbox" value="{{ $permission->id }}"
class="w-4 h-4 transition text-primary duration-300 rounded focus:ring-2 focus:ring-offset-0 focus:outline-none focus:ring-primary-200 dark:focus:ring-primary-700">
<label class="text-sm font-semibold text-gray-500 dark:text-gray-100">
{{ ucwords($permission->display_name) }}
</label>
</div>
#endforeach
</div>
</div>
In Livewire Component Class
public $role;
public $permissions;
public $selectedPermissions = [];
protected $listeners = ['eidtRole'];
public function mount()
{
$this->permissions = Permission::get();
}
public function eidtRole(Role $role)
{
$this->role = $role;
$this->selectedPermissions = $this->rolePermissions = $role->permissions()->pluck('id')->map(function ($id) {
return strval($id);
})->toArray();
}
After setting up my profile page my uploaded images initially produced an image on my local host. However lately it shows up as an icon instead https://i.stack.imgur.com/pp0Yt.png
I should note I am using php 7.3.19
profiles/index.blade.php
<div class="container">
<div class="row">
<div class="col-3 p-5">
<img src="{{ $user->profile->profileImage() }}" class="rounded-circle w-100">
</div>
<div class="col-9 pt-5">
<div class="d-flex justify-content-between align-items-baseline">
<div class="d-flex align-items-center pb-3">
<div class="h4">{{ $user->username }}</div>
<follow-button user-id="{{ $user->id }}" follows="{{ $follows }}"></follow-button>
</div>
#can('update', $user->profile)
Add New Post
#endcan
</div>
#can('update', $user->profile)
Edit Profile
#endcan
<div class="d-flex">
<div class="pr-5"><strong>{{ $postCount }}</strong> posts</div>
<div class="pr-5"><strong>{{ $followersCount }}</strong> followers</div>
<div class="pr-5"><strong>{{ $followingCount }}</strong> following</div>
</div>
<div class="pt-4 font-weight-bold">{{ $user->profile->title }}</div>
<div>{{ $user->profile->description }}</div>
<div>{{ $user->profile->url }}</div>
</div>
</div>
<div class="row pt-5">
#foreach($user->posts as $post)
<div class="col-4 pb-4">
<a href="/p/{{ $post->id }}">
<img src="/storage/{{ $post->image }}" class="w-100">
</a>
</div>
#endforeach
</div>
</div>
#endsection
Is there an issue in the way I am picking it up from the storage?
I used 'php artisan storage:link'
create.blade.php
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Image</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control{{ $errors->has('caption') ? ' is-invalid' : '' }}"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#if ($errors->has('caption'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('caption') }}</strong>
</span>
#endif
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#if ($errors->has('image'))
<strong>{{ $errors->first('image') }}</strong>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
PostsController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image'],
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Post $post)
{
return view('posts.show', compact('post'));
}
}
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Cache;
class ProfilesController extends Controller
{
public function index(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->id) : false;
$postCount = Cache::remember(
'count.posts.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->posts->count();
});
$followersCount = Cache::remember(
'count.followers.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->profile->followers->count();
});
$followingCount = Cache::remember(
'count.following.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->following->count();
});
return view('profiles.index', compact('user', 'follows', 'postCount', 'followersCount', 'followingCount'));
}
//($user = (User::findOrFail($user));)
//('user' => $user)
//
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'url' => 'url',
'image' => '',
]);
if (request('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000);
$image->save();
$imageArray = ['image' => $imagePath];
}
auth()->user()->profile->update(array_merge(
$data,
$imageArray ?? []
));
return redirect("/profile/{$user->id}");
}
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}
Use asset helper function to get the uploaded image URL.
<img src="{{ asset('storage/' . $post->image) }}" class="w-100">
OR
<img src="{{ asset(Storage::url($post->image)) }}" class="w-100">
I want to select a single category of questions that the user can select with options. I have tried doing this with a resource I found online.
The category page:
#foreach($categories as $category)
<section>
<a href="#" class="image">
<img src="{{asset('images/pic09.jpg')}}" alt="" data-position="top center" />
</a>
<div class="content">
<div class="inner">
<header class="major">
<h3>{{$category->name}}</h3>
</header>
<p></p>
<ul class="actions">
<li>Learn more</li>
</ul>
</div>
</div>
</section>
#endforeach
Here is the TestController I'm using, the show controller is might to select questions and options with the category_id at random:
namespace App\Http\Controllers;
use App\Category;
use App\Http\Requests\StoreTestRequest;
use App\Option;
class TestsController extends Controller
{
public function show($id)
{
$categories = Category::find($id)->with(
['categoryQuestions' => function ($query) {
$query->inRandomOrder()
->with(
['questionOptions' => function ($query) {
$query->inRandomOrder();
}]
);
}]
)
->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
public function store(StoreTestRequest $request)
{
$options = Option::find(array_values($request->input('questions')));
$result = auth()->user()->userResults()->create(
[
'total_points' => $options->sum('points')
]
);
$questions = $options->mapWithKeys(
function ($option) {
return [$option->question_id => [
'option_id' => $option->id,
'points' => $option->points
]
];
}
)->toArray();
$result->questions()->sync($questions);
return redirect()->route('client.results.show', $result->id);
}
}
web.php
// User
Route::group(['as' => 'client.', 'middleware' => ['auth']], function () {
Route::get('home', 'HomeController#redirect');
Route::get('dashboard', 'HomeController#index')->name('home');
Route::resource('/test', 'TestsController');
Route::get('results/{result_id}', 'ResultsController#show')->name('results.show');
Route::get('send/{result_id}', 'ResultsController#send')->name('results.send');
});
This is the Blade file from the resource I'm using:
#extends('layouts.home')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Test</div>
<div class="card-body">
#if(session('status'))
<div class="row">
<div class="col-12">
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
</div>
</div>
#endif
<form method="POST" action="{{ route('client.test.store') }}">
#csrf
#foreach($categories as $category)
<div class="card mb-3">
<div class="card-header">{{ $category->name }}</div>
<div class="card-body">
#foreach($category->categoryQuestions as $question)
<div class="card #if(!$loop->last)mb-3 #endif">
<div class="card-header">{{ $question->question_text }}</div>
<div class="card-body">
<input type="hidden" name="questions[{{ $question->id }}]" value="">
#foreach($question->questionOptions as $option)
<div class="form-check">
<input class="form-check-input" type="radio" name="questions[{{ $question->id }}]" id="option-{{ $option->id }}" value="{{ $option->id }}"#if(old("questions.$question->id") == $option->id) checked #endif>
<label class="form-check-label" for="option-{{ $option->id }}">
{{ $option->option_text }}
</label>
</div>
#endforeach
#if($errors->has("questions.$question->id"))
<span style="margin-top: .25rem; font-size: 80%; color: #e3342f;" role="alert">
<strong>{{ $errors->first("questions.$question->id") }}</strong>
</span>
#endif
</div>
</div>
#endforeach
</div>
</div>
#endforeach
<div class="form-group row mb-0">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
How can the Testcontroller be made to select questions and answer from a single category and save the result from the user's answers?
public function index()
{
$questions = Category::select('categories.name', 'question_result.points')
->join('questions', 'categories.id', '=', 'questions.category_id')
->join('question_result', 'questions.id', '=', 'question_result.question_id')
->join('results', 'question_result.result_id', '=', 'results.id')
->where('results.user_id', auth()->id())
->get();
return view('client.home', compact('questions'));
}