I'm creating a clone for a website where parents can create a list of things they need for their newborn baby so other people can buy it for them as a gift.
At this moment I've managed to insert data into my table and to link that row of data to the user id (so user who is logged in and completed the form).
I've managed to show all the lists from all the user id's but when I go to the dashboard of the authenticated user, I only want to show the lists who is linked to his user_id.
I can't get it working but I'm sure I have to use hasMany() and belongsTo().
This is my code:
My migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique;
$table->binary('password');
$table->enum('role', ['user','admin'])->default('user');
$table->timestamp('created_at');
$table->timestamp('updated_at');
});
Schema::create('lists', function (Blueprint $table)
{
$table->increments('id');
$table->foreignId('user_id')->nullable()->constrained()->onDelete('cascade');
$table->string('baby');
$table->string('vader');
$table->string('moeder');
$table->integer('telefoonnummer');
$table->string('email');
$table->string('adres');
$table->integer('huisnummer');
$table->string('toevoeging')->nullable();
$table->string('stad');
$table->integer('postcode');
$table->string('land');
});
}
My User model:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function birthLists()
{
return $this->hasMany(Birthlist::class, 'user_id');
}
}
My Birthlist model:
class Birthlist extends Model
{
use HasFactory;
protected $table = 'lists';
protected $primaryKey = 'id';
protected $fillable =
[
'user_id',
'baby',
'vader',
'moeder',
'telefoonnummer',
'email',
'adres',
'huisnummer',
'toevoeging',
'stad',
'postcode',
'land'
];
public $timestamps = false;
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
My controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Birthlist;
class DashController extends Controller
{
public function dashboard($id)
{
$userId = Auth::id();
$lists = Birthlist::where('user_id')->first();
return view('dashboard', [
'lists' => $lists,
]);
}
}
My view
<body class="bg-red-100 w-screen h-screen pb">
<main class="">
<div class="text-center p-8 bg-green-100">
<p class="">welkom</p>
<h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
</div>
<section class="bg-red-100">
<span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
#foreach ($lists->birthLists as $list)
<div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
<div class="text-3xl font-bold">
{{ $list->baby }}
</div>
<div class="flex flex-row justify-between">
{{ $list->vader }} & {{ $list->moeder }}
</div>
</div>
#endforeach
</section>
</main>
#include('partials.footer')
</body>
In User model :
public function birthLists()
{
return $this->hasMany(Birthlist::class);
}
and in view :
<body class="bg-red-100 w-screen h-screen pb">
<main class="">
<div class="text-center p-8 bg-green-100">
<p class="">welkom</p>
<h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
</div>
<section class="bg-red-100">
<span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
#foreach (auth()->user()->birthLists as $list)
<div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
<div class="text-3xl font-bold">
{{ $list->baby }}
</div>
<div class="flex flex-row justify-between">
{{ $list->vader }} & {{ $list->moeder }}
</div>
</div>
#endforeach
</section>
</main>
#include('partials.footer')
</body>
and don't need to get data from controller because you can get birthLists in blade file.
Related
hello I have 2 databases, namely users and profiles, profiles has a foreign key that is user_id. Then the relationship between the two is one to one.
Users migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Profiles migration
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('alamat')->nullable();
$table->string('nip')->nullable();
$table->string('jabatan')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
User Model
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne(Profile::class, 'user_id');
}
Profile Model
use HasFactory;
protected $table = 'profiles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Profile Controller
public function render()
{
$userProfile = Profile::where('user_id', Auth::user()->id)->first();
if (!$userProfile) {
$profile = new Profile();
$profile->user_id = Auth::user()->id;
$profile->save();
}
$user = User::find(Auth::user()->id);
return view('profile.index', ['user' => $user]);
}
Profile index.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
Your Profile!
<div>
<p>Nama :{{ $user->name }}</p>
<p>Email : {{ $user->email }}</p>
<p>Alamat : {{ $user->profile->alamat }}</p>
</div>
</div>
</div>
</div>
</div>
the code above produces an error that is Attempt to read property "address" on null. so how do i solve it?
On your render method, you can do something like this:
if(!\Auth::check()){
abort(401);
}
$user = \Auth::user();
$user->load('profile');
return view('profile.index', ['user' => $user]);
The above code is just the optimization with eager loading. This should give you the profile address:
$user->profile->alamat
Three things you have to confirm while doing this:
Is the user authenticated? If the user is not logged in you might not get data.
Is the route wrap in auth or similar middleware? If not, you might not get auth data.
Is there data in profiles table of the current user currently logged in?
While trying to create fake posts on laravel 8, I met with some errors, first it wasn't creating the posts, then I changed the username to nullable and it created it but I keep having;
Attempt to read property "username" on null
So, I went back to my database and I changed it back to none, but I still receive the same error code, I will post my codes now...
index.blade.php
#extends('layouts.app')
#section('content')
<div class="flex justify-center">
<div class="w-8/12 bg-white p-6 rounded-lg">
<form action="{{ route('posts') }}" method="post" class="mb-4">
#csrf
<div class="mb-4">
<label for="body" class="sr-only">Body</label>
<textarea name="body" id="body" cols="30" rows="4" class="by-gray-100 border-2
w-full p-4 rounded lg #error('body') border-red-500 #enderror" placeholder="Post something!"></textarea>
#error('body')
<div class="text-red-500 mt-3 text-sm">
{{$message}}
</div>
#enderror
</div>
<div>
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded
font-medium">Post</button>
</div>
</form>
#if ($posts->count())
#foreach ($posts as $post)
<div class="mb-4">
{{ $post->user->username }}
<span class="text-gray-600 text-sm">{{ $post->created_at->diffForHumans() }}</span>
<p class="mb-2">{{ $post->body }}</p>
</div>
#endforeach
{{ $posts->links() }}
#else
There are no posts...
#endif
</div>
</div>
#endsection
UserFactory.php
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'username' => $this->faker->username,
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany(Post::class);
}
}
PostFactory.php
<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'body' => $this->faker->sentence(20),
];
}
}
Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable= [
'body',
'user_id',
];
/**
* Get the user that owns the Post
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
It was because I had an existing user_id in my code so, I deleted it from the database and it worked
In table in view with data from products table I am traying to show names from user table but getting this error. I made Laravel relations in models and foreign keys. And added directory in product controller for user model.
Error: Trying to get property 'name' of non-object (View: /home/laravel/web/laravel.swt101.eu/public_html/abonamenty/resources/views/products/index.blade.php)
This is part of my controller for showing product data:
public function index()
{
$user = User::all('name','id');
$products = Product::sortable()->paginate(5);
return view('products.index',compact('products', 'user'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
This is part of view where I am getting this error
<td>{{ $product->user->name }}</td>
This is rest code of this view:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie abonamentami</h2>
</div>
<div class="col-md-4">
<form action="/search2" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('products.create') }}"> Utwórz nowy abonament</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('name', 'Nazwa usługi')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('category', 'Kategoria')</th>
<th scope="col">#sortablelink('launchdate', 'Data uruchomienia')</th>
<th scope="col">#sortablelink('expirationdate', 'Data wygasnięcia')</th>
<th scope="col">#sortablelink('renewalprice', 'Cena odnowienia')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->user->name }}</td>
<td>{{ $product->category }}</td>
<td>{{ $product->launchdate }}</td>
<td>{{ $product->expirationdate }}</td>
<td>{{ $product->renewalprice }}</td>
<td>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edytu</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $products ?? ''->appends(request()->except('page'))->render() !!}
#endsection
This is my product model:
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use Sortable;
protected $fillable = [
'name', 'detail', 'id', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'user_id', 'billingperiod', 'internalcost', 'status'
];
public $sortable = ['id', 'name', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'category', 'user_id'];
public function user()
{
return $this->belongsTo('App\User','user_id');
}
}
This is my user model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
use Sortable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'surname', 'showname', 'business', 'NIP', 'PESEL', 'address', 'city', 'postalcode', 'phone', 'comments',
];
public $primaryKey = 'id';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public $sortable = ['name',
'email',
'surname',
'showname',
'business',
'address',
'city',
'phone',
'role',
];
public function products()
{
return $this->hasMany('App\Product');
}
public function invoices()
{
return $this->hasMany('App\Invoice');
}
}
The error indicates that $product->user is probably returning null. Maybe not all products are associated with users for some reason.
Find the product id and look it up in the database, to see if it has a user connected.
In product model
you need to replace by this
return $this->belongsTo('App\User','user_id','id')
I tried to show the name of the creator of the post but I have an error
#section('content')
<div class="container" id="results">
<div class="row justify-content-center">
<div class="col-md-12" style="display: flex; flex-flow: row wrap;">
#foreach ($posts as $post)
<div class="col-md-3">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
<div class="card-body">
<h5 class="card-title">{{ $post->title }}</h5>
<small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
<span>Publié par {{ $post->username }}</span>
<p class="card-text">{{ $post->descriptionpost }}</p>
<p class="card-text">{{ $post->price }}</p>
Voir
</div>
</div>
#endforeach
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo('App\User');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'description' => $user->username
]);
});
}
public function getRouteKeyName()
{
return 'username';
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function following()
{
return $this->belongsToMany('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
}
}
ProfileController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->profile->id) : false;
return view('profile.show', compact('user', 'follows'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
PostController
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Poststore;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
public function index()
{
$posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(1000);
return view('welcome',['posts'=> $posts]);
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'title' => ['required', 'string'],
'image' => ['required', 'image'],
'price' => ['required', 'integer'],
'descriptionpost' => ['required', 'string']
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'title' => $data['title'],
'descriptionpost' => $data['descriptionpost'],
'price' => $data['price'],
'image' => $imagePath
]);
return redirect()->route('profile.show', ['user' => auth()->user() ]);
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function search(Request $request)
{
$words = $request->words;
$posts = DB::table('posts')->where('title', 'LIKE', '%$words%')->orWhere('descriptionpost', 'LIKE', '%$words%')->orderBy('created_at', 'DESC')->get();
return response()->json(['success' => true, 'posts' => $posts]);
}
}
My error:
Undefined property: stdClass::$username (View: /home/annonces/resources/views/welcome.blade.php)
Its my model post and user. Does anyone have an idea on how to resolve this? I don't know where the problem is located.
the problem is this line $post->username, you are trying to access username on post model which does not exist, first of all return the user model with the post as such
$post=post::find($id);
and in your view pass the $user to the view
#section('content')
<div class="container" id="results">
<div class="row justify-content-center">
<div class="col-md-12" style="display: flex; flex-flow: row wrap;">
#foreach ($posts as $post)
<div class="col-md-3">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
<div class="card-body">
<h5 class="card-title">{{ $post->title }}</h5>
<small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
<span>Publié par {{ $post->user->username }}</span>
<p class="card-text">{{ $post->descriptionpost }}</p>
<p class="card-text">{{ $post->price }}</p>
<a href="{{ route('posts.show', ['post' => $post->id]) }}" class="btn btn-
primary">Voir</a>
</div>
</div>
#endforeach
I have a page(admin.blade.php) that needs to display an amount. There is a button('change') present in the page, which calls upon a modal that takes an input. This modal is present inside the form whose action calls the 'change-goal' route which in turn gets the changeGoal function from the controller.
My admin.blade.php contains the form,modal and is as:
<a class="btn btn-primary" data-toggle="modal" data-target="#moneyModal">
<span class="glyphicon glyphicon-money glyphicon-white"></span>change</a>
<div class="modal fade" id="moneyModal" role="dialog">
<div class="modal-dialog">
<form method="post" action="change-goal">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Change Goal</h4>
</div>
<div class="modal-body">
<p>Please enter a new goal.</p>
</div>
<div class="modal-body">
<input class="form-control" name="newGoal" id="newGoal">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="save" type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
</div>
My controller is as:
public function changeGoal(Request $data) {
$newGoal =DB::table('user')->whereColumn('goal')->get();
$newGoal->updateGoal($data->goal);
return view('admin',compact('newGoal'));
}
My user model is:
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'goal'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function updateGoal($goal){
$this->goal = $goal;
$this->save();
}
I would like to display the value for newGoal on the admin.blade.php page. Currently I have {{ $newGoal }} written, but its giving me an error saying Undefined variable: newGoal .
I'm guessing the problem is within the controller.
How would I be able to save the value entered in that modal/form so
that I can see it every time I visit the page.
Also, here's the table in case its needed:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('password');
$table->integer('goal')->default(10000);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Would really appreciate the help.
EDIT:
My adminmanagement.blade.php (formerly admin.blade.php) is:
<p>Total Donations: <br> ${{ $price }}</p>
<p>Our Goal: {{ $newGoal }}</p>
<a class="btn btn-primary" data-toggle="modal" data-target="#moneyModal">
<span class="glyphicon glyphicon-money glyphicon-white"></span>change</a>
<div class="modal fade" id="moneyModal" role="dialog">
<div class="modal-dialog">
<form method="post" action="change-goal">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Change Goal</h4>
</div>
<div class="modal-body">
<p>Please enter a new goal.</p>
</div>
<div class="modal-body">
<input class="form-control" name="newGoal" id="newGoal">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="save" type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
</div>
web.php has:
Route::group(['middleware' => 'auth'], function () {
Route::get('/home', 'PagesController#getAllVideos')->name('/home');
Route::post('change-goal','PagesController#changeGoal')->name('change-goal');
Controller:
public function getAllVideos(){
$videos = Video::all();
$price = DB::table('donor')->sum('amount_donated');
return view('adminmanagement',compact(['videos','price']));
}
public function changeGoal(Request $data){
$newGoal = $data->input('newGoal');
auth()->user()->update([
'goal' => $newGoal
]);
return view('adminmanagement', compact('newGoal'));
}
User model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'goal'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function updateGoal($goal){
$this->goal = $goal;
$this->save();
return $this;
}
}
Based on your comments and your code, your input field is newGoal and not goal. Your user fetching query is wrong with the whereColumn condition missing the value. You're complicating a simple operation.
As per your comments all you need to do is update the goal of the logged in user (admin) and return the new goal value. Do this
public function changeGoal(Request $request)
{
$newGoal = $request->input('newGoal');
auth()->user()->update([
'goal' => $newGoal
]);
return view('admin', compact('newGoal'));
}
Edit : Based your comments. You should do this to keep things simple.
public function getAllVideos()
{
$videos = Video::all();
$price = DB::table('donor')->sum('amount_donated');
$goal = auth()->user()->goal;
return view('adminmanagement', compact('videos', 'price', 'goal'));
}
public function changeGoal(Request $data)
{
auth()->user()->update([
'goal' => $data->input('newGoal')
]);
return redirect('/home');
}
Change $newGoal to $goal in your view.
<p>Total Donations: <br> ${{ $price }}</p>
<p>Our Goal: {{ $goal }}</p>
inside model
public function updateGoal($goal){
$this->goal = $goal;
$this->save();
return $this;
}
and inside your controller
public function changeGoal(Request $data) {
$oldGoal =DB::table('user')->whereColumn('goal')->get();
$newGoal = $oldGoal->updateGoal($data->goal);
return view('admin',compact('newGoal'));
}