Laravel не прави update

C++ JAVA
Post Reply
User avatar
Ticketa
Турист
Турист
Posts: 571
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 24
Location: in /root
Contact:

Laravel не прави update

Post by Ticketa » Thu Oct 15, 2020 10:25 am

Привет, този laravel ми стана шуга и яко ме кефи хаха

Имам страница с настройки (глобални) обаче когато се опитват да презапиша настройките не ги записва (няма грешки няма нищо , което е странно прилагам controller и blade.

Code: Select all

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Carbon\Carbon;

use App\Mail\Contact;

use App\Property;
use App\Post;
use App\Comment;

use App\Setting;
use App\Message;
use App\User;
use Toastr;
use Auth;
use Hash;

class DashboardController extends Controller
{
    public function index()
    {
        $propertycount = Property::count();
        $postcount     = Post::count();
        $commentcount  = Comment::count();
        $usercount     = User::count();

        $properties    = Property::latest()->with('user')->take(5)->get();
        $posts         = Post::latest()->withCount('comments')->take(5)->get();
        $users         = User::with('role')->get();
        $comments      = Comment::with('users')->take(5)->get();

        return view('admin.dashboard', compact(
            'propertycount', 'postcount', 'commentcount', 'usercount',
            'properties',    'posts',     'users',        'comments'
        ));
    }


    public function settings()
    {
        $settings = Setting::first();

        return view('admin.settings.setting',compact('settings'));
    }

    public function settingStore(Request $request)
    {

        $this->validate($request, [
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);

        Setting::updateOrCreate(
            [ 'id'       => 1 ],
            [
              'name'     => $request->name,
              'email'    => $request->email,
              'phone'    => $request->phone,
              'address'  => $request->address,
              'footer'   => $request->footer,
              'aboutus'  => $request->aboutus,
              'facebook' => $request->facebook,
              'twitter'  => $request->twitter,
              'linkedin' => $request->linkedin
            ]
        );

        $settings = Setting::first();

        Toastr::success('message', 'Updated successfully.');
        return back();
    }


    public function changePassword()
    {
        return view('admin.settings.changepassword');

    }

    public function changePasswordUpdate(Request $request)
    {
        if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {

            Toastr::error('message', 'Your current password does not matches with the password you provided! Please try again.');
            return redirect()->back();
        }
        if(strcmp($request->get('currentpassword'), $request->get('newpassword')) == 0){

            Toastr::error('message', 'New Password cannot be same as your current password! Please choose a different password.');
            return redirect()->back();
        }

        $this->validate($request, [
            'currentpassword' => 'required',
            'newpassword' => 'required|string|min:6|confirmed',
        ]);

        $user = Auth::user();
        $user->password = bcrypt($request->get('newpassword'));
        $user->save();

        Toastr::success('message', 'Password changed successfully.');
        return redirect()->back();
    }


    public function profile()
    {
        $profile = Auth::user();

        return view('admin.settings.profile',compact('profile'));
    }

    public function profileUpdate(Request $request)
    {
        $request->validate([
            'name'      => 'required',
            'username'  => 'required',
            'email'     => 'required|email',
            'image'     => 'image|mimes:jpeg,jpg,png',
            'about'     => 'max:250'
        ]);

        $user = User::find(Auth::id());

        $image = $request->file('image');
        $slug  = str_slug($request->name);

        if(isset($image)){
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-admin-'.Auth::id().'-'.$currentDate.'.'.$image->getClientOriginalExtension();

            if(!Storage::disk('public')->exists('users')){
                Storage::disk('public')->makeDirectory('users');
            }
            if(Storage::disk('public')->exists('users/'.$user->image) && $user->image != 'default.png' ){
                Storage::disk('public')->delete('users/'.$user->image);
            }
            $userimage = Image::make($image)->stream();
            Storage::disk('public')->put('users/'.$imagename, $userimage);
            
        }else{
            $imagename = $user->image;
        }

        $user->name = $request->name;
        $user->username = $request->username;
        $user->email = $request->email;
        $user->image = $imagename;
        $user->about = $request->about;

        $user->save();

        return back();
    }


    // MESSAGE
    public function message()
    {
        $messages = Message::latest()->where('agent_id', Auth::id())->get();

        return view('admin.settings.messages.index',compact('messages'));
    }

    public function messageRead($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.readmessage',compact('message'));
    }

    public function messageReplay($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.replaymessage',compact('message'));
    }

    public function messageSend(Request $request)
    {
        $request->validate([
            'agent_id'  => 'required',
            'user_id'   => 'required',
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'message'   => 'required'
        ]);

        Message::create($request->all());

        Toastr::success('message', 'Message send successfully.');
        return back();

    }

    public function messageReadUnread(Request $request)
    {
        $status = $request->status;
        $msgid  = $request->messageid;

        if($status){
            $status = 0;
        }else{
            $status = 1;
        }

        $message = Message::findOrFail($msgid);
        $message->status = $status;
        $message->save();

        return redirect()->route('admin.message');
    }

    public function messageDelete($id)
    {
        $message = Message::findOrFail($id);
        $message->delete();

        Toastr::success('message', 'Message deleted successfully.');
        return back();
    }

    public function contactMail(Request $request)
    {
        $message  = $request->message;
        $name     = $request->name;
        $mailfrom = $request->mailfrom;

        Mail::to($request->email)->send(new Contact($message,$name,$mailfrom));

        Toastr::success('message', 'Mail send successfully.');
        return back();
    }
}

Code: Select all

@extends('backend.layouts.app')

@section('title', 'ОБЩИ НАСТРОЙКИ')

@push('styles')

@endpush


@section('content')

    <div class="block-header"></div>

    <div class="row clearfix">

        <div class="col-xs-12">
            <div class="card">
                <div class="header bg-indigo">
                    <h2>
                        ОБЩИ НАСТРОЙКИ
                        <a href="{{route('admin.profile')}}" class="btn waves-effect waves-light right headerightbtn">
                            <i class="material-icons left">person</i>
                            <span>ПРОФИЛ </span>
                        </a>
                    </h2>
                </div>
                <div class="body">
                    <form action="{{route('admin.settings.store')}}" method="POST">
                        @csrf
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="name" class="form-control" value="{{ $settings->name or null }}">
                                <label class="form-label">ЗАГЛАВИЕ НА САЙТА</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="email" name="email" class="form-control" value="{{ $settings->email or null }}">
                                <label class="form-label">МЕЙЛ</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="number" name="phone" class="form-control" value="{{ $settings->phone or null }}">
                                <label class="form-label">ТЕЛЕФОН</label>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="address" class="form-control" value="{{ $settings->address or null }}">
                                <label class="form-label">АДРЕС</label>
                            </div>
                            <small class="col-red font-italic">HTML таг е разрешен</small>
                        </div>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="footer" class="form-control" value="{{ $settings->footer or null }}">
                                <label class="form-label">Фуутър</label>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="form-line">
                                <textarea name="aboutus" rows="4" class="form-control no-resize">{{ $settings->aboutus or null }}</textarea>
                                <label class="form-label">ЗА КОМПАНИЯТА</label>
                            </div>
                        </div>

                        <h6>Social Links</h6>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="facebook" class="form-control" value="{{ $settings->facebook or null }}">
                                <label class="form-label">Facebook адрес</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="twitter" class="form-control" value="{{ $settings->twitter or null }}">
                                <label class="form-label">Twitter адрес</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="linkedin" class="form-control" value="{{ $settings->linkedin or null }}">
                                <label class="form-label">LinkedIn адрес</label>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-indigo btn-lg m-t-15 waves-effect">
                            <i class="material-icons">save</i>
                            <span>ЗАПОМНИ!</span>
                        </button>

                    </form>
                    
                </div>
            </div>
        </div>

    </div>

@endsection


@push('scripts')


@endpush

Model

Code: Select all

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'footer',
        'aboutus',
        'facebook',
        'twitter',
        'linkedin',
    ];
}

User avatar
Ticketa
Турист
Турист
Posts: 571
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 24
Location: in /root
Contact:

Re: Laravel не прави update

Post by Ticketa » Thu Oct 15, 2020 12:07 pm

Промених още няколко работи , но продължава да не ъпдейтва.

Добавих функцията save (бях е изпуснал) и при валидацията коригирах.

Продължавам да нямам грешки , но не ъпдейтва.

Code: Select all

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Carbon\Carbon;

use App\Mail\Contact;

use App\Property;
use App\Post;
use App\Comment;

use App\Setting;
use App\Message;
use App\User;
use Toastr;
use Auth;
use Hash;

class DashboardController extends Controller
{
    public function index()
    {
        $propertycount = Property::count();
        $postcount     = Post::count();
        $commentcount  = Comment::count();
        $usercount     = User::count();

        $properties    = Property::latest()->with('user')->take(5)->get();
        $posts         = Post::latest()->withCount('comments')->take(5)->get();
        $users         = User::with('role')->get();
        $comments      = Comment::with('users')->take(5)->get();

        return view('admin.dashboard', compact(
            'propertycount', 'postcount', 'commentcount', 'usercount',
            'properties',    'posts',     'users',        'comments'
        ));
    }


    public function settings()
    {
        $settings = Setting::first();

        return view('admin.settings.setting',compact('settings'));
    }

    public function settingStore(Request $request)
    {
        $request->validate([
        'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);
        /*
        
        $request->validate($request, [
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);*/

        Setting::updateOrCreate(
            [ 'id'       => 1 ],
            [
              'name'     => $request->name,
              'email'    => $request->email,
              'phone'    => $request->phone,
              'address'  => $request->address,
              'footer'   => $request->footer,
              'aboutus'  => $request->aboutus,
              'facebook' => $request->facebook,
              'twitter'  => $request->twitter,
              'linkedin' => $request->linkedin
            ]
        );

        $settings = Setting::first();
$settings->save();
        Toastr::success('message', 'Updated successfully.');
        return back();
    }


    public function changePassword()
    {
        return view('admin.settings.changepassword');

    }

    public function changePasswordUpdate(Request $request)
    {
        if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {

            Toastr::error('message', 'Your current password does not matches with the password you provided! Please try again.');
            return redirect()->back();
        }
        if(strcmp($request->get('currentpassword'), $request->get('newpassword')) == 0){

            Toastr::error('message', 'New Password cannot be same as your current password! Please choose a different password.');
            return redirect()->back();
        }

        $this->validate($request, [
            'currentpassword' => 'required',
            'newpassword' => 'required|string|min:6|confirmed',
        ]);

        $user = Auth::user();
        $user->password = bcrypt($request->get('newpassword'));
        $user->save();

        Toastr::success('message', 'Password changed successfully.');
        return redirect()->back();
    }


    public function profile()
    {
        $profile = Auth::user();

        return view('admin.settings.profile',compact('profile'));
    }

    public function profileUpdate(Request $request)
    {
        $request->validate([
            'name'      => 'required',
            'username'  => 'required',
            'email'     => 'required|email',
            'image'     => 'image|mimes:jpeg,jpg,png',
            'about'     => 'max:250'
        ]);

        $user = User::find(Auth::id());

        $image = $request->file('image');
        $slug  = str_slug($request->name);

        if(isset($image)){
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-admin-'.Auth::id().'-'.$currentDate.'.'.$image->getClientOriginalExtension();

            if(!Storage::disk('public')->exists('users')){
                Storage::disk('public')->makeDirectory('users');
            }
            if(Storage::disk('public')->exists('users/'.$user->image) && $user->image != 'default.png' ){
                Storage::disk('public')->delete('users/'.$user->image);
            }
            $userimage = Image::make($image)->stream();
            Storage::disk('public')->put('users/'.$imagename, $userimage);
            
        }else{
            $imagename = $user->image;
        }

        $user->name = $request->name;
        $user->username = $request->username;
        $user->email = $request->email;
        $user->image = $imagename;
        $user->about = $request->about;

        $user->save();

        return back();
    }


    // MESSAGE
    public function message()
    {
        $messages = Message::latest()->where('agent_id', Auth::id())->get();

        return view('admin.settings.messages.index',compact('messages'));
    }

    public function messageRead($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.readmessage',compact('message'));
    }

    public function messageReplay($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.replaymessage',compact('message'));
    }

    public function messageSend(Request $request)
    {
        $request->validate([
            'agent_id'  => 'required',
            'user_id'   => 'required',
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'message'   => 'required'
        ]);

        Message::create($request->all());

        Toastr::success('message', 'Message send successfully.');
        return back();

    }

    public function messageReadUnread(Request $request)
    {
        $status = $request->status;
        $msgid  = $request->messageid;

        if($status){
            $status = 0;
        }else{
            $status = 1;
        }

        $message = Message::findOrFail($msgid);
        $message->status = $status;
        $message->save();

        return redirect()->route('admin.message');
    }

    public function messageDelete($id)
    {
        $message = Message::findOrFail($id);
        $message->delete();

        Toastr::success('message', 'Message deleted successfully.');
        return back();
    }

    public function contactMail(Request $request)
    {
        $message  = $request->message;
        $name     = $request->name;
        $mailfrom = $request->mailfrom;

        Mail::to($request->email)->send(new Contact($message,$name,$mailfrom));

        Toastr::success('message', 'Mail send successfully.');
        return back();
    }
}

mapka7a
Турист
Турист
Posts: 249
Joined: Mon Sep 05, 2011 9:21 am
Answers: 20
Location: Sofia
Contact:

Re: Laravel не прави update

Post by mapka7a » Thu Oct 15, 2020 2:24 pm

Ticketa wrote:
Thu Oct 15, 2020 12:07 pm
Промених още няколко работи , но продължава да не ъпдейтва.

Добавих функцията save (бях е изпуснал) и при валидацията коригирах.

Продължавам да нямам грешки , но не ъпдейтва.

Code: Select all

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Carbon\Carbon;

use App\Mail\Contact;

use App\Property;
use App\Post;
use App\Comment;

use App\Setting;
use App\Message;
use App\User;
use Toastr;
use Auth;
use Hash;

class DashboardController extends Controller
{
    public function index()
    {
        $propertycount = Property::count();
        $postcount     = Post::count();
        $commentcount  = Comment::count();
        $usercount     = User::count();

        $properties    = Property::latest()->with('user')->take(5)->get();
        $posts         = Post::latest()->withCount('comments')->take(5)->get();
        $users         = User::with('role')->get();
        $comments      = Comment::with('users')->take(5)->get();

        return view('admin.dashboard', compact(
            'propertycount', 'postcount', 'commentcount', 'usercount',
            'properties',    'posts',     'users',        'comments'
        ));
    }


    public function settings()
    {
        $settings = Setting::first();

        return view('admin.settings.setting',compact('settings'));
    }

    public function settingStore(Request $request)
    {
        $request->validate([
        'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);
        /*
        
        $request->validate($request, [
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);*/

        Setting::updateOrCreate(
            [ 'id'       => 1 ],
            [
              'name'     => $request->name,
              'email'    => $request->email,
              'phone'    => $request->phone,
              'address'  => $request->address,
              'footer'   => $request->footer,
              'aboutus'  => $request->aboutus,
              'facebook' => $request->facebook,
              'twitter'  => $request->twitter,
              'linkedin' => $request->linkedin
            ]
        );

        $settings = Setting::first();
$settings->save();
        Toastr::success('message', 'Updated successfully.');
        return back();
    }


    public function changePassword()
    {
        return view('admin.settings.changepassword');

    }

    public function changePasswordUpdate(Request $request)
    {
        if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {

            Toastr::error('message', 'Your current password does not matches with the password you provided! Please try again.');
            return redirect()->back();
        }
        if(strcmp($request->get('currentpassword'), $request->get('newpassword')) == 0){

            Toastr::error('message', 'New Password cannot be same as your current password! Please choose a different password.');
            return redirect()->back();
        }

        $this->validate($request, [
            'currentpassword' => 'required',
            'newpassword' => 'required|string|min:6|confirmed',
        ]);

        $user = Auth::user();
        $user->password = bcrypt($request->get('newpassword'));
        $user->save();

        Toastr::success('message', 'Password changed successfully.');
        return redirect()->back();
    }


    public function profile()
    {
        $profile = Auth::user();

        return view('admin.settings.profile',compact('profile'));
    }

    public function profileUpdate(Request $request)
    {
        $request->validate([
            'name'      => 'required',
            'username'  => 'required',
            'email'     => 'required|email',
            'image'     => 'image|mimes:jpeg,jpg,png',
            'about'     => 'max:250'
        ]);

        $user = User::find(Auth::id());

        $image = $request->file('image');
        $slug  = str_slug($request->name);

        if(isset($image)){
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-admin-'.Auth::id().'-'.$currentDate.'.'.$image->getClientOriginalExtension();

            if(!Storage::disk('public')->exists('users')){
                Storage::disk('public')->makeDirectory('users');
            }
            if(Storage::disk('public')->exists('users/'.$user->image) && $user->image != 'default.png' ){
                Storage::disk('public')->delete('users/'.$user->image);
            }
            $userimage = Image::make($image)->stream();
            Storage::disk('public')->put('users/'.$imagename, $userimage);
            
        }else{
            $imagename = $user->image;
        }

        $user->name = $request->name;
        $user->username = $request->username;
        $user->email = $request->email;
        $user->image = $imagename;
        $user->about = $request->about;

        $user->save();

        return back();
    }


    // MESSAGE
    public function message()
    {
        $messages = Message::latest()->where('agent_id', Auth::id())->get();

        return view('admin.settings.messages.index',compact('messages'));
    }

    public function messageRead($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.readmessage',compact('message'));
    }

    public function messageReplay($id)
    {
        $message = Message::findOrFail($id);

        return view('admin.settings.messages.replaymessage',compact('message'));
    }

    public function messageSend(Request $request)
    {
        $request->validate([
            'agent_id'  => 'required',
            'user_id'   => 'required',
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'message'   => 'required'
        ]);

        Message::create($request->all());

        Toastr::success('message', 'Message send successfully.');
        return back();

    }

    public function messageReadUnread(Request $request)
    {
        $status = $request->status;
        $msgid  = $request->messageid;

        if($status){
            $status = 0;
        }else{
            $status = 1;
        }

        $message = Message::findOrFail($msgid);
        $message->status = $status;
        $message->save();

        return redirect()->route('admin.message');
    }

    public function messageDelete($id)
    {
        $message = Message::findOrFail($id);
        $message->delete();

        Toastr::success('message', 'Message deleted successfully.');
        return back();
    }

    public function contactMail(Request $request)
    {
        $message  = $request->message;
        $name     = $request->name;
        $mailfrom = $request->mailfrom;

        Mail::to($request->email)->send(new Contact($message,$name,$mailfrom));

        Toastr::success('message', 'Mail send successfully.');
        return back();
    }
}
id primary key ли е? Правилно ли е изписано, може да го сетнеш експлицитно в модела
protected $primaryKey = 'id';
сетнал ли си $fillable полетата в модела?

User avatar
Ticketa
Турист
Турист
Posts: 571
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 24
Location: in /root
Contact:

Re: Laravel не прави update

Post by Ticketa » Thu Oct 15, 2020 3:12 pm

mapka7a wrote:
Thu Oct 15, 2020 2:24 pm
id primary key ли е? Правилно ли е изписано, може да го сетнеш експлицитно в модела
protected $primaryKey = 'id';
сетнал ли си $fillable полетата в модела?
Вероятно ми е смешен въпроса - Какво означава експлицитно ?

Относно модела - да, сметнати са полетата

Code: Select all

protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'footer',
        'aboutus',
        'facebook',
        'twitter',
        'linkedin',
    ];
Относно primary key - да


PRIMARY BTREE Да


Code: Select all

CREATE TABLE `settings` (
  `id` int(10) UNSIGNED NOT NULL,
  `sitename` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `footer` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `aboutus` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `facebook` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `twitter` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `linkedin` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

mapka7a
Турист
Турист
Posts: 249
Joined: Mon Sep 05, 2011 9:21 am
Answers: 20
Location: Sofia
Contact:

Re: Laravel не прави update

Post by mapka7a » Thu Oct 15, 2020 5:37 pm

Ticketa wrote:
Thu Oct 15, 2020 3:12 pm
mapka7a wrote:
Thu Oct 15, 2020 2:24 pm
id primary key ли е? Правилно ли е изписано, може да го сетнеш експлицитно в модела
protected $primaryKey = 'id';
сетнал ли си $fillable полетата в модела?
Вероятно ми е смешен въпроса - Какво означава експлицитно ?

Относно модела - да, сметнати са полетата

Code: Select all

protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'footer',
        'aboutus',
        'facebook',
        'twitter',
        'linkedin',
    ];
Относно primary key - да


PRIMARY BTREE Да


Code: Select all

CREATE TABLE `settings` (
  `id` int(10) UNSIGNED NOT NULL,
  `sitename` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `footer` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `aboutus` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `facebook` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `twitter` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `linkedin` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Няма смешен въпрос.
Експлицитно = изрично.
Аз не виждам да имаш primary key в SQL-а на таблицата

Code: Select all

`id` int(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
не помня как точно се правеше вече :D

ако направиш
$result = updateOrCreate...
dd($result)

каква е стойността на $result

User avatar
Ticketa
Турист
Турист
Posts: 571
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 24
Location: in /root
Contact:

Re: Laravel не прави update

Post by Ticketa » Fri Oct 16, 2020 7:01 am

Нямам представа поради каква причина , но като дебъгна заявката чрез dd($result) нищо не се визуализира.

mapka7a
Турист
Турист
Posts: 249
Joined: Mon Sep 05, 2011 9:21 am
Answers: 20
Location: Sofia
Contact:

Re: Laravel не прави update

Post by mapka7a » Fri Oct 16, 2020 12:51 pm

Ticketa wrote:
Fri Oct 16, 2020 7:01 am
Нямам представа поради каква причина , но като дебъгна заявката чрез dd($result) нищо не се визуализира.
Каква е стойността на validate

Code: Select all

$this->validate($request, [
            'name'      => 'required',
            'email'     => 'required',
            'phone'     => 'required',
            'address'   => 'required',
            'footer'    => 'required',
            'aboutus'   => 'required',
            'facebook'  => 'required|url',
            'twitter'   => 'required|url',
            'linkedin'  => 'required|url',
        ]);
минава ли успешно , дебъгни $errors в темплейта , ако ги подаваш, ако не ги подай да видим какво се случва там. Май не стига до update... заявката

User avatar
deam0n
Web-tourist
Web-tourist
Posts: 3036
Joined: Sat Oct 01, 2005 4:33 pm
Answers: 204
Location: Шопландия
Contact:

Re: Laravel не прави update

Post by deam0n » Fri Oct 16, 2020 2:07 pm

Оправи ли си ID да ти е primary key?

User avatar
Ticketa
Турист
Турист
Posts: 571
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 24
Location: in /root
Contact:

Re: Laravel не прави update

Post by Ticketa » Fri Oct 16, 2020 2:27 pm

deam0n wrote:
Fri Oct 16, 2020 2:07 pm
Оправи ли си ID да ти е primary key?
Да

joTunkiq
Потребител
Потребител
Posts: 830
Joined: Tue Dec 25, 2012 10:03 am
Answers: 142
Contact:

Re: Laravel не прави update

Post by joTunkiq » Fri Oct 16, 2020 4:33 pm

Пробвай модела Setting.php да го нарпавиш така:

Code: Select all

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $guarded = ['id']; // туй ща оправи в живота
    protected $table = 'settings'; // не е задълже, ама нека да го има

    protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'footer',
        'aboutus',
        'facebook',
        'twitter',
        'linkedin',
    ];
}
Допълнително, ако продължава да не работи, може би се насочи към "по-неприята" алтернатива в контролера:

Code: Select all

<?php 

// ... 

$setting =  Setting::first();
if(!$setting) $setting = new Setting;
// според PHP версията сигурно може да го направиш още по яко =>   $setting =  Setting::first() ?: new Setting;  //яко, а?
// Вариант 1: да си абсолютно точен .. 
// $setting->fill(request()->only(['email','email','phone','address','footer','aboutus','facebook','twitter','linkedin']));

 //  вариянт 2 : ако инпута ти е същия като базата данни и все пак това е админа, може да си позволиш малко своеволия (в кръга на шегата и семплотата на примера):
$setting->fill(request()->all()); // задължително трябва да имаш $fillable, което съвпадне го попълва
$setting->save();
:think:

Post Reply